KMc*_*McA 2 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
Run Code Online (Sandbox Code Playgroud)
这两个都没有把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
Run Code Online (Sandbox Code Playgroud)
不同的是console.log,alert只需要一个参数.你需要连接字符串:
alert("you can not lift " + this.name + ".");
Run Code Online (Sandbox Code Playgroud)
有了它,两者lantern.take();和Item.take.call(lantern);- 相当 - 都会警告"你不能举起黄铜灯笼.",而你的第三个例子取决于当前执行中this关键字的值.顺便说一下,你的take功能没有参数.
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |