JS函数有bug

时间:2015-08-11 19:03:42

标签: javascript html

以下代码应显示带有输入值的警报,但不会显示。

我做错了什么?

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;
&#13;
&#13;

2 个答案:

答案 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 + '!');
};

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:1)

问题在于这个匿名函数:

function(name) {
   this.greet(name);
}

不受Greeter上下文约束。 所以在这里被称为:

this.tellName = function(name) {
  callback(name);
};

this指向没有Namer方法的greet对象,因此会产生this.greet is not a function错误。