关于js原型链继承的一些复习
1 function Person(name, age) { 2 this.name = name, 3 this.age = age, 4 this.run = function () { 5 console.log(this.name + "在敲代码!"); 6 } 7 } 8 9 Person.prototype.race = function () { 10 console.log("这是原型链上的方法!"); 11 } 12 13 let a = new Person('wangwu', 99); 14 console.log(a.age); 15 a.run(); 16 a.race();
1.静态继承
Person.sing = function () { console.log(this.name + "在唱歌!"); } Person.sing();
2.冒充继承(就是改变了this的指向)
优:可以向父代传参;
缺:无法继承原型链
function Caller() { Person.call(this,'lisi', 56) } let p = new Caller(); // p.run(); p.run(); console.log(p.age);
3.原型链继承
优:可以继承原型链
缺:无法向父代传参
function extendFunc(){} extendFunc.prototype =new Person(); let t = new extendFunc('lplp',147); t.run() t.race(); console.log(t.name);
4.混合继承
优:互补2.3,既能向父代传参,又能继承原型链
function func(){ Person.call(this,'lihua',66) } func.prototype = new Person(); let y = new func(); y.run();