Javascript继承-“;这";关键字丢失绑定?

Javascript继承-“;这";关键字丢失绑定?,javascript,inheritance,prototype,this,Javascript,Inheritance,Prototype,This,我正试图学习Javascript中更高级的继承方法,但我不明白为什么我的继承对象在下面的示例代码中失去了来自雄辩的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 b

我正试图学习Javascript中更高级的继承方法,但我不明白为什么我的继承对象在下面的示例代码中失去了来自雄辩的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
但这两个都不能把这个名字和灯笼联系起来?在调用对象原型中定义的方法时,我缺少/不理解什么?多谢各位

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

console.log
不同,它只接受一个参数。您需要对字符串进行压缩:

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

这样,两个
lantern.take()和<代码>项.取.叫(灯笼)-等效-将警告“您不能提起黄铜灯笼”,而第三个示例取决于当前执行中的值。顺便说一句,您的
take
函数不接受参数。

不要覆盖
Object.prototype。使用非标准行为创建
。不要在
Object.prototype
中放入任何内容period@Bergi:您正在考虑
对象。创建
。在
对象上没有标准的
create
。prototype
@user1689607:噢,对了。尽管如此,Esailija是正确的哇!非常感谢。是的,这本书使用了一个“虚构”的打印功能,我将其编辑为“警告”进行测试。这是有史以来最简单的答案!非常感谢。