我有这个代码:
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();
Run Code Online (Sandbox Code Playgroud)
我希望能够使用'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();
Run Code Online (Sandbox Code Playgroud)
谢谢.
您可以使用.bind强制函数的所有者成为您传递的任何对象.所以,你可以这样编写你的Person对象:
function Person(name){
this.name = name;
var hello = function(){
alert("hello " + this.name);
}.bind(this);
return {
hello: hello
};
}
Run Code Online (Sandbox Code Playgroud)
这将确保.hello始终在Person调用它的上下文中执行.
这是一个演示:
默认情况下,在使用new关键字时不使用return 函数将返回,this
您将需要更改函数的声明方式.
这是一个小提琴
http://jsfiddle.net/SaintGerbil/9SAhD/
function Person(name){
this.name = name;
this.hello = function (){
alert("hello " + this.name);
}
}
var newPerson = new Person("john");
newPerson.hello();?
Run Code Online (Sandbox Code Playgroud)
编辑如果您要求名称是私人的,那么这里是另一种选择
function Person(name){
var _name = name;
this.hello = function (){
alert("hello " + _name);
}
}
var newPerson = new Person("john");
newPerson.hello();?
Run Code Online (Sandbox Code Playgroud)
在回答你的问题时,有4种方法可以调用函数.这些方法会影响this它们的价值
new关键字)where this是自动返回的新对象.this调用该对象.this成为全局对象,(在没有new的情况下调用contstructor时常见的错误)进一步编辑
因此,在开始时采用您想要的代码并解释发生了什么.
function Person(name){
this.name = name; // 1
function hello(){ // 2
alert("hello " + this.name); // 3
}
return {
hello: hello
}; //4
}
Run Code Online (Sandbox Code Playgroud)
作为函数的人可以通过两种方式调用:
var x = Person("ted");
和
var x = new Person("jimmy");
由于您已使用大写命名Person,这意味着您希望人们使用new.
所以坚持我们输入函数,javascript创建一个新对象并分配给它this.
this并用传递的参数初始化.this.this(默认行为)我们现在声明一个新对象并将该函数附加到它.这个新对象的范围没有'name'变量.因此,当您创建对象时,您会获得一个附加了函数的对象,但它无法获取正确执行的变量.这就是你得到未定义的原因.
这是否有意义当我不得不扩展文本框时,我总是担心我会胡扯?
或者,如果我尽可能详细地写出你的函数,它会看起来像这样.
function Person(name){
var this = new Object();
this.name = name;
var hello = function (){
alert("hello " + this.name);
}
this.hello = hello;
var that = new Object();
that.hello = hello;
return that;
}
Run Code Online (Sandbox Code Playgroud)