gpt4 book ai didi

javascript - 用javascript中的对象替代 'self = this'

转载 作者:行者123 更新时间:2023-12-02 05:27:09 25 4
gpt4 key购买 nike

我有这个代码:

function Person(name){      
var self = this;

this.name = name;

function hello(){
alert("hello " + self.name);
}

return {
hello: hello
};
}

var newPerson = new Person("john");

newPerson.hello();

我希望能够使用“this”关键字来访问“hello”函数中的“name”属性;我想要使​​用“self”变量的替代方法。

除了使用 jquery 的 $.proxy 函数来控制上下文,我如何编写相同的代码但没有变量'self'?

我想要一个如下所示的代码,但当我调用“newPerson.hello()”时,“name”始终为“undefined”。我不知道为什么,因为我一直认为函数的范围始终是调用者点左侧的对象,在这种情况下,在创建时为“newPerson”分配了值“john”对象。

function Person(name){              
this.name = name;

function hello(){
alert("hello " + this.name);
}

return {
hello: hello
};
}

var newPerson = new Person("john");

newPerson.hello();

谢谢。

最佳答案

您可以使用 .bind 强制函数的所有者成为您传递的任何对象。因此,您可以像这样编写您的 Person 对象:

function Person(name){ 
this.name = name;

var hello = function(){
alert("hello " + this.name);
}.bind(this);

return {
hello: hello
};
}

这将确保 .hello 始终在调用它的 Person 的上下文中执行。

这是一个演示:

--- jsFiddle DEMO ---

关于javascript - 用javascript中的对象替代 'self = this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12301642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com