js继承的几种方式
2017-04-22 00:00
435 查看
1、原型继承
2、构造函数继承
3、构造函数和原型组合继承
4、寄生式继承
"use strict"; /* * 每一个构造函数都有一个原型对象 * 每一个原型对象都包含一个指向构造函数的指针 * 每一个对象都包含一个指针指向原型对象 * 原型对象==实例对象 * 原型对象就包含一个指针指向原型对象 * 结论:层次递进,就构成了原型链 */ function GrandFather(){ this.name = "张三"; } GrandFather.prototype.getName = function () { return this.name; } function Parent() { } Parent.prototype = new GrandFather(); function Child(){ } Child.prototype = new Parent(); var child = new Child(); alert(child.getName());
2、构造函数继承
"use strict"; //父子关系,子类的构造函数里调用父类的构造函数 function Parent() { this.name = "李四"; this.age = 12; } function Child() { Parent.call(this); } var child = new Child(); alert(child.name); alert(child.age);
3、构造函数和原型组合继承
"use strict"; //组合继承(将构造函数和原型链结合在一起) function Parent() { this.name = "李四"; this.age = 12; } Parent.prototype.getName = function(){ alert(this.name); } function Child() { Parent.call(this); } Child.prototype = new Parent(); var child = new Child(); alert(child.getName());
4、寄生式继承
"use strict"; //寄生式继承 function CreateOther(original){ var clone = Object(original); clone.getName = function () { alert(this.name); } return clone; } var person = { name:"张三", age:"11" } var otherPerson = CreateOther(person); person.getName();