首页 > 代码库 > JavaScript面向对象编程(11)其他继承方式

JavaScript面向对象编程(11)其他继承方式

1、将父对象作为新对象的原型

function object(o) {
	var n;
	function F() {}
	F.prototype = o;
	n = new F();
	n.uber = o;
	return n;
}

var shape = {
	name: 'Shape',
	toString: function(){
			if(this.uber)
				return this.uber.toString() + ', ' + this.name;
			else
				return this.name;
		}
}
var twoDShape = object(shape);
twoDShape.name = "2 D Shape";
alert(twoDShape.toString());


2、在子构造器中调用父构造器Parent.apply();并传递参数,这样与父对象的this绑定的属性同时成为子对象的属性

function Shape(id) {
	this.id = id;

}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){return this.name;};

function Triangle() {
	Shape.apply(this, arguments);//原生属性继承
}



JavaScript面向对象编程(11)其他继承方式