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();