JS的对象继承this
这是一个单继承spa
//Shape - superclass function Shape() { this.x = 0; this.y = 0; } Shape.prototype.move = function(x, y) { this.x += x; this.y += y; console.info("Shape moved."); }; // Rectangle - subclass function Rectangle() { Shape.call(this); //call super constructor. } Rectangle.prototype = Object.create(Shape.prototype); var rect = new Rectangle(); rect instanceof Rectangle //true. rect instanceof Shape //true. rect.move(1, 1); //Outputs, "Shape moved."
这是一个多继承prototype
function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); } MyClass.prototype = Object.create(SuperClass.prototype); //inherit mixin(MyClass.prototype, OtherSuperClass.prototype); //mixin MyClass.prototype.myMethod = function() { // do a thing };
有了上面两个例子,咱们总结一下指针
继承分两个方面,实例部分跟原型部分code
实例部分用call改写this指针加载orm
原型部分用Object.create将原形链复制过去对象
固然,能够用别的方法继承,譬如:new SuperClass() 而后再添加实例、原型等方法继承
普及一下Object.createip
Object.create()
方法建立一个拥有指定原型和若干个指定属性的对象。ci
Object.create(proto, [ propertiesObject ])
proto
一个对象,做为新建立对象的原型。
propertiesObject
可选。该参数对象是一组属性与值,该对象的属性名称将是新建立的对象的属性名称,值是属性描述符(这些属性描述符的结构与Object.defineProperties()
的第二个参数同样)。注意:该参数对象不能是 undefined
,另外只有该对象中自身拥有的可枚举的属性才有效,也就是说该对象的原型链上属性是无效的。
若是 proto 参数不是 null
或一个对象值,则抛出一个 TypeError
异常。