apply()的这种用法在Javascript中意味着什么 [英] what does this usage of apply() means in Javascript
问题描述
请有人告诉我,下面的代码中 this.init.apply(this,arguments)
做了什么?
我理解 apply()
通常会做什么,但在下面的代码中,它在那里做了什么?
var Class = function(){
var klass = function(){
this.init.apply(这个,论点); //我真的不明白......
};
klass.prototype.init = function(){};
返回klass;
};
var Person = new Class;
//用法
var someone = new Person;
我看到很多人都在使用它。我已经知道它的作用但不能真正把它放在上面所以我需要更多光线。
我上升了一个额外的水平JS,所以我想知道它的一切,而不仅仅是简单的'Hello world'级别。
非常感谢
apply
是函数对象的成员函数。假设我们有: function saySomething(thing,anotherThing){
alert(this +say+ thing + 和+ anotherThing);
}
然后我们可以使用:
saySomething.apply(document,[hello,goodbye]);
这将调用函数并将数组的值作为参数提供给函数。第一个参数是函数的 context (或者,当函数运行时,这个等于)。
您还应该知道 arguments
是一个特殊变量,它包含传递给函数的所有参数的数组。所以,在这里, this.init.apply(this,arguments)
意味着调用 init
函数并将其全部传递传递给 klass
构造函数的参数。
在实际实现中,我认为 init
会期望参数。考虑如何在没有 apply
的情况下完成此操作:
var klass = function (arg1,arg2,arg3){
init(arg1,arg2,arg3);
}
klass.prototype.init = function(arg1,arg2,arg3){}
如果你想将 arg4
添加到init,你可以在三个地方添加它!通过让 klass
透明地将其所有参数传递给 init
,可以使代码更加脆弱。
Please, can someone tell me what does this.init.apply(this, arguments)
do in the code below?
I understand what apply()
does in general, but in the context of the code below, what is it doing in there?
var Class = function() {
var klass = function() {
this.init.apply(this, arguments); //I don't really get this bit...
};
klass.prototype.init = function(){};
return klass;
};
var Person = new Class;
//Usage
var someone = new Person;
I see a lot of people using it. I've got an idea of what it does but can't really put my hands on it so I need more light.
I'm going up an extra level in JS, so I wanna know everything about it, not just the simple 'Hello world' level.
Many thanks
apply
is a member function of a function object. Suppose we have:
function saySomething(thing, anotherThing) {
alert(this + " says " + thing + " and " + anotherThing);
}
Then we can use:
saySomething.apply(document, ["hello", "goodbye"]);
This calls the function and supplies the values of the array as arguments to the function. The first argument species the context of the function (or, what this
equals when the function runs).
You should also be aware that arguments
is a special variable that holds an array of all arguments passed to the function. So, here, this.init.apply(this, arguments)
means that the init
function is called and passed all the of arguments that were passed to the klass
constructor.
In a real implementation, I think init
would expect arguments. Consider how this would be done without apply
:
var klass = function(arg1, arg2, arg3) {
init(arg1, arg2, arg3);
}
klass.prototype.init = function(arg1, arg2, arg3) {}
If you wanted to add arg4
to init, you'd have add it in three places! By having klass
transparently pass all its arguments to init
, you make you code much less brittle.
这篇关于apply()的这种用法在Javascript中意味着什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!