我不明白为什么会出现以下代码:
function Foo() {
this.a = "a";
this.c = add();
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
alert("obj2.b is " + obj2.b); //obj2.b is Undefined
这段代码不会为 obj2 创建“b”属性:
function Foo() {
this.a = "a";
this.func1 = add;
this.c = this.func1();
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
alert("obj2.b is " + obj2.b); // obj2.b is added
将创建“b”属性。
我是 JS 的新手,我尝试阅读有关使用函数作为构造函数的内容,基本上我明白了,但我想我仍然缺少一些东西。
谢谢你,
诺姆
最佳答案
the value of this is determined by how a function is called.
如果没有调用者,那么 this
将指向默认/全局范围(窗口)。
如果您需要将上下文传递给另一个函数,您应该使用以下之一:.apply
、.bind
示例
function Foo() {
this.a = "a";
this.c = add.apply(this);
}
var add = function() {
this.b = "added";
}
obj2 = new Foo();
console.log("obj2.b is " + obj2.b); //obj2.b is Undefined
关于javascript - JS通过构造器调用函数为对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038402/