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

一、使用 call 方法调用父构造函数

       在一个子构造函数中,你能够经过调用父构造函数的 call 方法来实现继承,相似于 Java 中的写法。下例中,使用 Food 和 Toy 构造函数建立的对象实例都会拥有在 Product 构造函数中添加的 name 属性和 price 属性,但 category 属性是在各自的构造函数中定义的。函数

二、语法

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

1)参数:

thisArgthis

     在 fun 函数运行时指定的 this 值。if(thisArg == undefined|null) this = window,if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()spa

arg1, arg2, ...code

     指定的参数列表。对象

2)返回值:

     使用调用者提供的 this 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefinedblog

3)描述:继承

call() 容许为不一样的对象分配和调用属于一个对象的函数/方法。ip

call() 提供新的 this 值给当前调用的函数/方法。你能够使用 call 来实现继承:写一个方法,而后让另一个新的对象来继承它(而不是在新对象中再写一次这个方法)。get

相关文章
相关标签/搜索