2017-01-16 73 views
1

我有一只狗构造如下:访问“这”在构造一个独立的函数中

var Dog = function(name,type) 
{ 
    this.name = name; 
    this.type = type; 
    this.normalObjFunc = function() 
    { 
     this.name = "kl"; 
    } 
    var retfunc = function() 
    { 
     return this.name; 
    } 
    return retfunc; 
} 

retfunc()函数,我试图访问this.name下列方式。

var dogObj = new Dog("hj","labrador"); 
alert(dogObj()); 

在输出中,我得到尽可能的警报信息框“结果”,我没有得到什么的O/P“结果”,意味着什么?

我有意不包括retfunc到“这个”对象,这是否意味着我不能访问this.nameretfunc()因为一个单独的“这”会被创造出来的?

我也意识到分配var self =this解决了这个问题。 我只是想知道什么是“结果”这是输出,为什么不undefined理想?

+2

你现在的样子执行返回的功能使得'this'引用全局窗口对象,所以你AE实际上得到'window.name'这是一个包含的名称的窗口属性窗户 –

回答

2

问题是因为this范围内的功能将是window。您需要缓存在一个变量的对象引用和调用,就像这样:

var Dog = function(name, type) { 
 
    var _this = this; 
 
    
 
    this.name = name; 
 
    this.type = type; 
 
    
 
    this.normalObjFunc = function() { 
 
     _this.name = "kl"; 
 
    } 
 
    
 
    var retfunc = function() { 
 
     return _this.name; 
 
    } 
 
    return retfunc; 
 
} 
 

 
var dogObj = new Dog("hj", "labrador"); 
 
console.log(dogObj());

另外,您可以prototype的功能,以保持this范围,但是你需要改变你的逻辑,因为这意味着Dog()的返回值不能作为函数。

var Dog = function(name, type) {   
 
    this.name = name; 
 
    this.type = type; 
 
} 
 

 
Dog.prototype.normalObjFunc = function() { 
 
    this.name = "kl"; 
 
} 
 
Dog.prototype.retfunc = function() { 
 
    return this.name; 
 
} 
 

 
var dogObj = new Dog("hj", "labrador"); 
 
console.log(dogObj.retfunc());

相关问题