一直以来对Javascript的原型、原型链、继承等东西都只是会用和了解,但没有深入去理解这门语言关于继承这方面的本质和特点。闲暇之余做的理解和总结,欢迎各位朋友一起讨论。
本文本主要从两段代码的区别说明继承:
function Parent(){
this.Name='parent';
}
Parent.prototype.getName = function(){
return this.Name;
}
Parent.prototype.Share = ["Share"];
function Child(){
Parent.call(this)
this.Age = 'Age'
}
Child.prototype = Parent.prototype; //原型继承
var _child = new Child();
var _parent = new Parent();
Parent.prototype.Foo = "Foo";
_parent.Share.push('second');
console.log(_child.Share);
console.log("_child instanceof Child: " + ( _child instanceof Child ));
console.log("_child instanceof Parent: " + ( _child instanceof Parent));
console.log("Child.prototype.isPrototypeOf(_child): " + Child.prototype.isPrototypeOf(_child));
console.log("Parent.prototype.isPrototypeOf(_child): " + Parent.prototype.isPrototypeOf(_child));
console.log("_child.hasOwnProperty('Share'): " + _child.hasOwnProperty('Share'));
console.log("_parent.hasOwnProperty('Share'): " + _parent.hasOwnProperty('Share'));
console.log("_child.hasOwnProperty('Name'): " + _child.hasOwnProperty('Name'));
console.log("_parent.hasOwnProperty('Name'): " + _parent.hasOwnProperty('Name'));
function Parent(){
this.Name='parent';
}
Parent.prototype.getName = function(){
return this.Name;
}
Parent.prototype.Share = ["Share"];
function Child(){
Parent.call(this)
this.Age = 'Age'
}
function Inher(supers, childs) {
function F(){}
F.prototype = supers.prototype;
F.prototype.constructor = childs;
return new F();
}
Child.prototype = Inher(Parent,Child); //原型对象继承
var _child = new Child();
var _parent = new Parent();
_parent.Share.push('second');
Parent.prototype.Foo = "Foo";
console.log(_child.Share);
console.log("_child instanceof Child: " + (_child instanceof Child));
console.log("_child instanceof Parent: " + (_child instanceof Parent));
console.log("Child.prototype.isPrototypeOf(_child): " + Child.prototype.isPrototypeOf(_child));
console.log("Parent.prototype.isPrototypeOf(_child): " + Parent.prototype.isPrototypeOf(_child));
console.log("_child.hasOwnProperty('Share'): " + _child.hasOwnProperty('Share'));
console.log("_parent.hasOwnProperty('Share'): " + _parent.hasOwnProperty('Share'));
console.log("_child.hasOwnProperty('Name'): " + _child.hasOwnProperty('Name'));
console.log("_parent.hasOwnProperty('Name'): " + _parent.hasOwnProperty('Name'));
从结果可以看出两段代码的运行结果是一致的。
不同之处:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有