Javascript继承 - “this”关键字失去绑定?

时间:2012-11-28 19:43:35

标签: javascript inheritance prototype this

我正在尝试在Javascript中学习更高级的继承方法,并且无法弄清楚为什么我的继承对象在Eloquent Javascript的示例代码中丢失了它的“this”关键字绑定。

我试过调用take()函数,例如使用:

lantern.take(); // alerts you can not lift
Item.take.call(lantern, "the brass lantern"); // alerts you can not lift
lantern.take.call(this, "the brass lantern"); // alerts you can not lift

这些都没有将this.name绑定到灯笼吗?在我调用对象原型中定义的方法的方法中,我缺少什么/不理解?谢谢。

function forEachIn(object, action) {
  for (var property in object) {
    if (object.hasOwnProperty(property))
      action(property, object[property]);
  }
}

function clone(object) {
  function OneShotConstructor(){}
  OneShotConstructor.prototype = object;
  return new OneShotConstructor();
}

Object.prototype.create = function() {
  var object = clone(this);
  if (typeof object.construct == "function")
    object.construct.apply(object, arguments);
  return object;
};

Object.prototype.extend = function(properties) {
  var result = clone(this);
  forEachIn(properties, function(name, value) {
    result[name] = value;
  });
  return result;
};

var Item = {
  construct: function(name) {
    this.name = name;
  },
  inspect: function() {
    alert("it is ", this.name, ".");
  },
  kick: function() {
    alert("klunk!");
  },
  take: function() {
    alert("you can not lift ", this.name, ".");
  }
};

var lantern = Item.create("the brass lantern");
lantern.kick(); // alerts klunk

1 个答案:

答案 0 :(得分:5)

console.log不同,alert只接受一个参数。你需要连接字符串:

alert("you can not lift " + this.name + ".");

这样,同等的lantern.take();Item.take.call(lantern);都会警告“你不能抬起黄铜灯笼。”,而你的第三个例子取决于{{3}的价值。在当前的执行中。顺便说一句,你的take函数没有参数。

相关问题