在JavaScript中,沒有繼承關鍵字: extends。那麼,它是透過哪些方法,在用建構子產生物件時,把物件基於另外一個建構函數,進行屬性的生成(繼承/拷貝)的呢? 即:對一個函數使用 new 關鍵字產生物件時,其物件的屬性,可以來自於其它函數。
本文提供兩種寫法:
第一種(非正式):
但需要理解此用法。
Javascript代碼
function Animal (name, age){
this.name
function Dog (name, age){
this .i = Animal;
this.i(name, age);
}
console.log(d);
/*
Dog {name: "hello", age: 20}
age: 20 name: "hello"
__proto__:
constructor: function Dog(name, age)
*/
上面一個寫法是引用外在函數Animal 作為自己的一個內部成員函數。這是一種匿名函數的寫法。
相當於:
Javascript代碼 function Dog (name, age){ this.name = name; this.age = age;
}
this.i(name, age);
}
age){
/*
When calling a function, instead of using the 'new' keyword to create
object,
🎠
Animal();
new Animal( );
The inner 'this' is the same one of the outer ated inside of the function, so it has to
refer to the outer one.
*/
this.i = function // 2. so the inner "this" is the same
this.age = age; // one of the outer "this".
}
this.i(name, age); created.
}
思考:呼叫函數時,"this"是誰? ?
既然,函數呼叫不產生 "this" 物件。
那麼直接在 Dog 內呼叫 Animal 不可以嗎?
答案:否
Java代碼
/*
Which 'this' the called alled function refers to that 'this' object.
*/
function Dog (name, age){ // if call Animal directly,
belongs to 'window', } of Animal refers to 'window'
第二種(正式):
使用 apply() or call() toappin
使用 apply() call it.
Javascript代碼
function Animal (name, age){
} function Dog (name, age){ Animal.apply(this, arguments); // apply "this" object to Animal function. // or call Animal function with a given 'this' instead of referring to other 'this'. } d = new Dog('hello',20);
.
/* Dog {name: " hello", age: 20} age: 20 name: "hello"tion Dog(name, age)
*/