javascript 原型和“this”闭包访问
我是js初学者,对下面的代码感到困惑:
Foo = function(arg) {
this.arg = arg;
};
Foo.prototype = {
init: function () {
var f = function () {
alert("current arg: " + this.arg); // am expecting "bar", got undefined
}
f();
}
};
var yo = Foo("bar");
yo.init();
我本来期望得到“current arg: bar”,但得到“current arg: undefined”。我注意到,首先将 this.arg 复制到“正常”变量中,然后在闭包中引用此变量即可:
Foo.prototype = {
init: function () {
var yo = this.arg;
var f = function () {
alert("current arg: " + yo); }
f();
}
};
我是否做错了什么,得到了错误的期望,或者它是否落入了 js WTF 之一?
I am a beginner in js, and am puzzled by the following code:
Foo = function(arg) {
this.arg = arg;
};
Foo.prototype = {
init: function () {
var f = function () {
alert("current arg: " + this.arg); // am expecting "bar", got undefined
}
f();
}
};
var yo = Foo("bar");
yo.init();
I was expected to get "current arg: bar", but got "current arg: undefined". I noticed that by copying this.arg into a "normal" variable first, and refering this variable in the closure works:
Foo.prototype = {
init: function () {
var yo = this.arg;
var f = function () {
alert("current arg: " + yo); }
f();
}
};
Am I doing something wrong, got wrong expectations, or does it fall into one of the js WTF ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Vanilla 函数将通过
this
引用window
来运行。您的第二段代码是如何使用闭包解决此问题的完美示例。(您还可以使用
call
和apply
来调用具有特定上下文的函数。)Vanilla functions will be run with
this
referring towindow
. Your second piece of code is a perfect example of how to work around this problem using closures.(You can also use
call
andapply
to call a function with a particular context.)这取决于函数的调用方式。
如果使用关键字 new 调用,则 this 引用正在构造的对象(将在函数末尾隐式返回)。
如果作为普通函数调用,
this
引用全局window
对象。示例:
JavaScript 本身没有“构造函数”,JavaScript 知道您的
function
实际上是“构造函数”的唯一方法是调用样式(即您使用关键字new
每当你调用它时)It depends on how the function was invoked.
If invoked with keyword
new
thenthis
refers to the object being constructed (which will be implicitly returned at the end of the function).If invoked as a normal function,
this
refers to the globalwindow
object.Example:
JavaScript doesn't have "constructors" per se, the only way JavaScript knows that your
function
is actually a "constructor" is invokation style (namely you using keywordnew
whenever you invoke it)