JavaScript——call() 方法


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'; } var cheese = new Food('feta', 5); var fun = new Toy('robot', 40);

1、使用 call 方法調用父構造函數

       在一個子構造函數中,你可以通過調用父構造函數的 call 方法來實現繼承,類似於 Java 中的寫法。下例中,使用 Food 和 Toy 構造函數創建的對象實例都會擁有在 Product 構造函數中添加的 name 屬性和 price 屬性,但 category 屬性是在各自的構造函數中定義的。

2、語法

fun.call(thisArg, arg1, arg2, ...)

1)參數:

thisArg

     在 fun 函數運行時指定的 this 值。if(thisArg == undefined|null) this = window,if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()

arg1, arg2, ...

     指定的參數列表。

2)返回值:

     使用調用者提供的 this 值和參數調用該函數的返回值。若該方法沒有返回值,則返回 undefined

3)描述:

call() 允許為不同的對象分配和調用屬於一個對象的函數/方法。

call() 提供新的 this 值給當前調用的函數/方法。你可以使用 call 來實現繼承:寫一個方法,然后讓另外一個新的對象來繼承它(而不是在新對象中再寫一次這個方法)。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM