以下代码应显示带有输入值的警报,但不会显示。
我做错了什么?
(Demo)
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>
&#13;
答案 0 :(得分:3)
从this
移除this.greet(name)
,将this.greet = function(name)
替换为function greet(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);
}
&#13;
<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>
&#13;
答案 1 :(得分:1)
问题在于这个匿名函数:
function(name) {
this.greet(name);
}
不受Greeter上下文约束。 所以在这里被称为:
this.tellName = function(name) {
callback(name);
};
this
指向没有Namer
方法的greet
对象,因此会产生this.greet is not a function
错误。