JS function with bug
JS function with bug
下面的代码应该显示一个带有输入值的警告,但是它没有。
我做错了什么?
(演示)function greetings(greeting, name) {
var Greeter = function(greeting, name) {
namer.onName(function(name) {
this.greet(name);
});
this.greet = function(name) {
window.alert(greeting + ', ' + name + '!');
};
};
var Namer = function() {
var callback;
this.onName = function(cb) {
callback = cb;
};
this.tellName = function(name) {
callback(name);
};
};
var namer = new Namer();
var greeter = new Greeter(greeting, name);
namer.tellName(name);
}
<p>
Something:
<input id="greeting" type="text" value="Bye!" />SomeName:
<input id="name" type="text" value="Jack" />
<input type="button" value="Greet!" onclick="greetings(document.getElementById('greeting').value, document.getElementById('name').value)" />
</p>
从this.greet(name)
中去掉this
,用function greet(name)
代替this.greet = function(name)
。
namer.onName(function(name) {
greet(name);
});
function greet(name) {
window.alert(greeting + ', ' + name + '!');
};
function greetings(greeting, name) {
var Greeter = function(greeting, name) {
namer.onName(function(name) {
greet(name);
});
function greet(name) {
window.alert(greeting + ', ' + name + '!');
};
};
var Namer = function() {
var callback;
this.onName = function(cb) {
callback = cb;
};
this.tellName = function(name) {
callback(name);
};
};
var namer = new Namer();
var greeter = new Greeter(greeting, name);
namer.tellName(name);
}
<p>
Something:
<input id="greeting" type="text" value="Bye!" />SomeName:
<input id="name" type="text" value="Jack" />
<input type="button" value="Greet!" onclick="greetings(document.getElementById('greeting').value, document.getElementById('name').value)" />
</p>
问题是这个匿名函数:
function(name) {
this.greet(name);
}
没有绑定到Greeter上下文。所以在这里它被称为:
this.tellName = function(name) {
callback(name);
};
this
指向没有greet
方法的Namer
对象,因此产生this.greet is not a function
错误
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- Bug with chrome.tabs.captureVisibleTab
- Three.js - bug with shadows
- Weird bug with Accounts.onCreatedUser
- JS function with bug
- Workaround for bug with 0th <select> option in Mobile
- Angular.js bug with safari?
- IE-Bug with JQuery-Slider