在Javascript中使用它
我已经阅读了一些规则,以确定在Javascript的不同场景中,在Javascript中使用它,javascript,node.js,this,Javascript,Node.js,This,我已经阅读了一些规则,以确定在Javascript的不同场景中,this的值。一切都很好,直到下面的例子把我甩了 function Person(name){ this.name = name; //this is the object when function used as constructor (as expected) this.changeName = someFunction(); // produces error function someFunction(){
this
的值。一切都很好,直到下面的例子把我甩了
function Person(name){
this.name = name; //this is the object when function used as constructor (as expected)
this.changeName = someFunction(); // produces error
function someFunction(){
this.nickName = this.name+"by"; //this is now the global object and not the instance, thus the name property does not exist.
}
}
var a = new Person ('bob'); //error due to the function in changeName property.
据我所知,this
变量在通过点符号调用时占用调用对象的值,或者在与new
关键字一起使用时占用新构造函数的值
有人能解释一下为什么上面函数中的this语句是全局对象而不是新实例化的对象吗
有人能解释一下为什么上面函数中的this语句是全局对象而不是新实例化的对象吗
因为当您将(n unbound)函数调用为func()
时,此
将引用全局对象(如果函数处于严格模式,则为未定义的
)
每个函数(箭头函数除外)都有自己的值。因此,您将Person
作为new Person()
调用,并且this
内部Person
引用了一个新对象,这一事实对someFunction
中的this
值没有任何影响。这只关系到如何someFunction
您可以调用someFunction
,并通过以下方式显式设置其this
值:
另请参见:在someFunction()中的此将引用全局对象,因为它位于函数调用中。请参阅更全面、更完整的解释
如果您希望解决此问题,请在父级中使用别名this
function Person(name){
var self = this; // Store a reference to the current instance
self.name = name;
self.changeName = someFunction(); // Odd that you'd capture the return value of a setter, ...
function someFunction(){
self.nickName = self.name+"by"; //self references the instance, creating the property.
}
}
它回答了我的实现不正确的原因。非常感谢。当我意识到里面是全局对象时,我已经在修复中使用了call()函数,但是我需要一个原因来知道为什么它是全局对象。这就是我想要的解释(Y)。
function Person(name){
var self = this; // Store a reference to the current instance
self.name = name;
self.changeName = someFunction(); // Odd that you'd capture the return value of a setter, ...
function someFunction(){
self.nickName = self.name+"by"; //self references the instance, creating the property.
}
}