call()允許將屬于一個對象的函數(shù)/方法分配給另一個對象并對其進行調(diào)用。
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = "food";
}
document.write(new Food("cheese", 12).name);測試看看?/?示例中call()向函數(shù)/方法提供一個新的值this。 通過調(diào)用,您可以編寫一次方法,然后在另一個對象中繼承該方法,而不必為新對象重寫該方法。
您可以使用call()來鏈接對象的構(gòu)造函數(shù),類似于Java。
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = "food";
}
function Toy(name, price) {
Product.call(this, name, price);
this.category = "toy";
}
let cheese = new Food("cheese", 12);
let robot = new Toy("robot", 85);測試看看?/?在下面的示例中,我們在不傳遞參數(shù)的情況下調(diào)用了display函數(shù):
var name = "Seagull";
function display() {
document.write(this.name);
}
display.call();測試看看?/?