2014-03-01 46 views
1

test.testHello(helloWorld.sayHello);运行时,它不能识别我插入了新的问候语,因为问候语是未定义的。我可以使用bind来确保它在适当的范围内运行,但我不确定为什么它不在适当的范围内运行。有人可以解释为什么会发生这种情况并向我展示更好的解为什么我的回调失去了它的范围?

解决方案:test.testHello(helloWorld.sayHello.bind(helloWorld));

http://jsfiddle.net/EzabX/

var HelloWorldClass = function() { 


this.greetings = []; 
} 
HelloWorldClass.prototype.addGreeting = function(greeting) { 
    this.greetings.push(greeting); 
} 
HelloWorldClass.prototype.sayHello = function() { 
    document.getElementById('output').innerHTML += this.greetings; 
    this.greetings.forEach(function(greeting) { 
     greeting.execute();   
    }) 
} 

var TestClass = function() { 
    this.testHello = function(callback) { 
     alert("TestHello is working, now callback"); 
     callback(); 
    } 
} 


var main = function() { 
    var helloWorld = new HelloWorldClass(); 
    var test = new TestClass(); 
    helloWorld.addGreeting({ 
     execute: function() { 
      alert("Konichiwa!"); 
     } 
    }); 
    helloWorld.sayHello(); 

    test.testHello(helloWorld.sayHello); 
} 

main(); 
+2

你说什么范围? – Vinz243

+0

另一种考虑它的方式是'this'不是对建筑环境/范围的参考。它是对函数的* invoker *的引用。谁或调用'callback'?不是'helloWorld'。 'bind'给你一个调用者稳定的函数 –

回答

0

管理原型函数范围内this变量调用时作为回调可以是复杂的新用户使用。你并不总是需要一个类的所有功能的原型。如果你真的想用一个原型函数来看看Javascript .bind(this)的实现。谷歌和Stackoverflow是你在这个话题上的朋友。例如:Preserving a reference to "this" in JavaScript prototype functions

问题的代码与this指DOM窗口对象,而不是一个HelloWorld实例:

this.greetings.forEach(function(greeting) { 
     greeting.execute();   
    }) 

非原型版本的作品好了,简单易用。小提琴:http://jsfiddle.net/EzabX/2/

var HelloWorldClass = function() { 
    var greetings = []; 

    this.greetings = greetings; 

    this.addGreeting = function(greeting) { 
     greetings.push(greeting); 
    }; 

    this.sayHello = function() { 
     document.getElementById('output').innerHTML += greetings; 
     greetings.forEach(function(greeting) { 
     greeting.execute();   
     }) 
    }; } 
+0

'问候'没有什么错。你认为在那个片段中究竟是什么感觉? – Bergi

+0

'this'指的是Window而不是HelloWorld。不确定工作答案和其他工作答案的正确链接是如何投票的。调整了违规行。 –

+0

在'helloWorld.addGreeting(...)'调用中,'this * * does *指向'helloWorld'。我没有因为链接而失望,但是由于错误的术语(“范围”),错误的解释以及几乎没有帮助的代码建议。 – Bergi

相关问题