原型链: 一个对象通过proto指向另一个对象,访问一个对象时
就能拥有另外一个对象的属性
function Parent(){
this.x =1;
this.y =2;
}
Parent.prototype.say = function(){
console.log('say');
}
function Child(name){
Parent.apply(this, arguments)
this.z = 3
}
var copy = function(){}
copy.prototype = Parent.prototype
Child.prototype = new copy()
//Child.prototype.__proto__= Parent.prototype 避免使用
// Child.prototype = Object.create(Human.prototype) 不兼容IE
var x = new Child()
//Child {x: 1, y: 2, z: 3}
image
注意
该属性没有写入 ES6 的正文,而是写入了附录,原因是proto前后的双下划线,说明它本质上是一个内部属性,而不是一个正式的对外的 API ,只是由于浏览器广泛支持,才被加入了 ES6 。标准明确规定,只有浏览器必须部署这个属性,其他运行环境不一定需要部署,而且新的代码最好认为这个属性是不存在的。因此,无论从语义的角度,还是从兼容性的角度,都不要使用这个属性,而是使用下面的Object.setPrototypeOf()(写操作)、Object.getPrototypeOf()(读操作)、Object.create()(生成操作)代替。
参考:
MDN
使用类的继承方法
class Parent{
constructor(){
this.a = 1;
this.b = 2;
}
say(){
console.log('say')
}
}
class Child extends Parent{
constructor(){
super()
this.c =3
}
cry(){
console.log('cry')
}
}
var x = new Child()
网友评论