Sha*_*aoz 9 javascript jquery web-applications
请问,有人可以告诉我this.init.apply(this, arguments)下面的代码做了什么吗?
我理解apply()一般情况下是什么,但在下面的代码中,它在那里做了什么?
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;
Run Code Online (Sandbox Code Playgroud)
我看到很多人都在使用它.我已经知道它做了什么,但不能真正把它放在手上,所以我需要更多光线.
我在JS上升了一个级别,所以我想知道它的一切,而不仅仅是简单的'Hello world'级别.
非常感谢
apply是函数对象的成员函数.假设我们有:
function saySomething(thing, anotherThing) {
alert(this + " says " + thing + " and " + anotherThing);
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以使用:
saySomething.apply(document, ["hello", "goodbye"]);
Run Code Online (Sandbox Code Playgroud)
这将调用该函数并将该数组的值作为参数提供给该函数.第一个参数包含函数的上下文(或者,this当函数运行时等于什么).
您还应该知道这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) {}
Run Code Online (Sandbox Code Playgroud)
如果你想添加arg4到init,你可以在三个地方添加它!通过klass透明地传递其所有参数init,您可以使代码更不易碎.
| 归档时间: |
|
| 查看次数: |
2147 次 |
| 最近记录: |