问题描述
任何人都可以解释上下文在Javascript中使用 call
和 apply
方法吗?
为什么要使用调用
和应用
而不是直接调用函数?
您使用或到功能。从本质上讲,这意味着您要执行一个函数,就好像它是特定对象的方法一样。两者之间的唯一区别是调用
期望参数用逗号分隔,而 apply
期望数组中的参数。 / p>
来自,其中构造函数被链接:
function产品(名称,价格){
this.name = name;
this.price = price;
if(price< 0)
抛出RangeError('无法创建产品''+名+',负价格');
返回此;
}
函数食品(名称,价格){
Product.apply(this,arguments);
this.category ='food';
}
Food.prototype = new Product();
函数玩具(名称,价格){
Product.apply(this,arguments);
this.category ='toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta',5);
var fun = new Toy('机器人',40);
什么 Product.apply(this,arguments)
确实如下: Product
构造函数作为函数应用于每个 Food
和<$ c $中c>玩具构造函数,并且每个对象实例都以此
的形式传递。因此,每个食物
和玩具
现在都有 this.name
和 this.category
属性。
Guys can any one explain context to use call
and apply
methods in Javascript?
Why to use call
and apply
instead of calling a function directly ?
You use call
or apply
when you want to pass a different this
value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call
expects parameters separated by commas, while apply
expects parameters in an array.
An example from Mozilla's apply
page, where constructors are chained:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product "' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
What Product.apply(this, arguments)
does is the following: The Product
constructor is applied as a function within each of the Food
and Toy
constructors, and each of these object instances are being passed as this
. Thus, each of Food
and Toy
now have this.name
and this.category
properties.
这篇关于上下文使用调用并在Javascript中应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!