到目前为止我以为我理解了 javascript 作用域的工作原理。这就是我所拥有的
function MFCommentsHandler(node, type, item) {
this.get = function(returnType){
...
}
function getButton(){
var button = document.createElement('button'),
get = this.get;
button.innerHTML = 'Load more comments';
button.onclick = function(){
console.log(get);
get('html');
}
return button;
}
}
我使用内部函数将 getButton
生成的元素附加到文档中,但是当我单击它时,我得到 get is not a function
。为什么 get
在 onclick
函数中未定义?
最佳答案
this
仅取决于调用函数的方式。它可以是隐式的,但就你而言,你失去了上下文。您需要将 this
缓存在上部范围中:
function MFCommentsHandler(node, type, item) {
var self = this;
this.get = function(returnType){
...
}
function getButton(){
self.get(); // cached reference
...
}
}
或者您可以在调用 getButton
时显式传递上下文:
function MFCommentsHandler(node, type, item) {
this.get = function(returnType){
...
}
function getButton(){
this.get();
...
}
getButton.call(this); // explicit context
...
关于JavaScript 作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21174283/