可能重复:
Why does a method'sthis
change when calling a reference to an object's method?
我以为我知道一点JavaScript,但我注意到如果你从一个变量执行一个方法,它会改变它。我试图找到有关这方面的信息,但大多数文章都谈到了call,apply,bind,event handlers / callbacks等。
var dog = {
bark: function(){
console.log('woof');
},
speak: function(){
this.bark();
}
};
// Test 1
dog.speak(); //woof
// Test 3
var speak = dog.speak
speak(); //TypeError: Object #<Object> has no method 'bark'
答案 0 :(得分:-1)
我认为您需要将var
设置为除发言之外的其他内容。你需要去:
var speaking_var = dog.speak();
speaking_var();
修复拼写错误(您在;
之后忘了var speak = dog.speak
)