java速学教程(入门到精通)
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
<code>function person(name,age){ this.name = name; this.age = age; } person.prototype.say = function(){ console.log(this.name+":"+this.age); } function superman(name,age){ person.call(this,name,age); } superman.prototype = new person(); var s = new superman('superman',29); </code>
在书上看到这种继承方式,说很完美,可是我并不觉得啊,因为他的superman.prototype = new person();
这句,会将父类的实例属性添加到子类的原型上啊,虽然person.call(this,name,age);
已经拿到了父类的实例属性,但是感觉这样污染了子类的原型啊,怎么破?
<code>function object(obj){ function F(){} F.prototype = obj; return new F(); } function inheritProtoType(SuperType,SubType){ var prototype = object(SuperType.prototype); prototype.constructor = SubType; SubType.prototype = prototype; } function SuperType(){ this.name = 'yuhualingfeng'; this.friends = ['David','Bob','Lucy']; } SuperType.prototype.saySuperName = function(){ console.log(this.name); }; function SubType(){ SuperType.call(this); this.age = 30; } inheritProtoType(SuperType,SubType); SubType.prototype.saySubName = function(){ console.log(this.name); }; var subType = new SubType(); </code>
<code>function person(name,age){ this.name = name; this.age = age; } person.prototype.say = function(){ console.log(this.name+":"+this.age); } function superman(name,age){ person.call(this,name,age); } superman.prototype = new person(); var s = new superman('superman',29); </code>
在书上看到这种继承方式,说很完美,可是我并不觉得啊,因为他的superman.prototype = new person();
这句,会将父类的实例属性添加到子类的原型上啊,虽然person.call(this,name,age);
已经拿到了父类的实例属性,但是感觉这样污染了子类的原型啊,怎么破?
<code>function object(obj){ function F(){} F.prototype = obj; return new F(); } function inheritProtoType(SuperType,SubType){ var prototype = object(SuperType.prototype); prototype.constructor = SubType; SubType.prototype = prototype; } function SuperType(){ this.name = 'yuhualingfeng'; this.friends = ['David','Bob','Lucy']; } SuperType.prototype.saySuperName = function(){ console.log(this.name); }; function SubType(){ SuperType.call(this); this.age = 30; } inheritProtoType(SuperType,SubType); SubType.prototype.saySubName = function(){ console.log(this.name); }; var subType = new SubType(); </code>
Object.create(Person.prototype);
这个可以有效解决,不过要注意兼容性
<code>function create(obj) { if (Object.create) { return Object.create(obj); } function f() {}; f.prototype = obj; return new f(); }</code>
继承 person.prototype
继承而不是污染
Java免费学习笔记:立即学习
解锁 Java 大师之旅:从入门到精通的终极指南
已抢7358个
抢已抢95516个
抢已抢14970个
抢已抢52817个
抢已抢196025个
抢已抢87526个
抢