JavaScript继承-原型链继承
作者:互联网
//原型链继承 function SuperType(){ this.name = 'super'; this.girlFriends = ["xiaoli","xiaowang"]; } SuperType.prototype.sayName = function(){ console.log(this.name); } function SubType(){ this.age = 20; } //创建SuperType的实例赋给SubType的原型 //实现继承的本质是重写原型对象,代之以一个新类型的实例 SubType.prototype = new SuperType(); SubType.prototype.sayAge = function(){ console.log(this.age); } var sub1 = new SubType(); sub1.sayName(); //super sub1.sayAge(); //20 //现在sub.constructor指向SuperType //是因为原来SubType的constructor被重写的缘故 console.log(sub1.constructor); //输出的SuperType函数 //原型链的问题 //通过以下代码,我们会发现SubType的所有实例都会共享这girlFriends属性 //SuperType构造函数是会被SubType的所有实例所共享的 var sub2 = new SubType(); sub1.girlFriends.push("xiaochen"); console.log(sub2.girlFriends); //(3) ["xiaoli", "xiaowang", "xiaochen"]
标签:console,log,sub1,继承,JavaScript,girlFriends,SubType,原型,SuperType 来源: https://www.cnblogs.com/gehaoyu/p/11804272.html