1. 原型链继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function Father(name) { this.name = name; }
Father.prototype.sayName = function() { console.log("name is " + this.name); }
var father = new Father("a"); father.sayName();
function Child(name) { this.name = name; }
Child.prototype = new Father(); var child = new Child("c"); child.sayName();
|
输出:
2. 通过 call() apply()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function Father(name) { this.name = name; this.sayName = function() { console.log("name is " + this.name); } }
function Child(name,age) { Father.apply(this,[name]); this.age = age; this.sayAge = function() { console.log("age is " + this.age); } }
var child = new Child("c","21"); child.sayName(); child.sayAge();
|
输出:
3. 原型链和 call() apply() 混合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
function Father(name) { this.name = name; } Father.prototype.sayName = function() { console.log("name is " + this.name); }
function Child(name,age) { Father.call(this,name); this.age = age; } Child.prototype = new Father();
Child.prototype.sayAge = function() { console.log("age is " + this.age); }
var child = new Child("c",21); child.sayName(); child.sayAge();
|
输出:
4. 对象冒充
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Father(name) { this.name = name; this.sayName = function() { console.log("name is " + this.name); } }
function Child(name) { this.child = Father; this.child(name); delete this.child; }
var child = new Child("c"); child.sayName();
|
输出:
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏