【发布时间】:2016-11-18 22:17:27
【问题描述】:
在 JavaScript 中让我感到困惑的是:在下面的代码中,我有一个包含一个属性的对象构造函数。在它下面,我添加了一些原型方法。方法 'method1' 能够很好地访问 'this.property',它返回值 30。方法 'combine' 只是调用了 'method1',但它返回 NaN。似乎“this.property”对第一次调用是公开的,但不是第二次调用。为什么会有这种奇怪的行为?
var ObjBuilder = function()
{
this.property = 3;
};
ObjBuilder.prototype = function()
{
var method1 = function()
{
return this.property * 10;
}
var combine = function()
{
return method1() + 2;
}
return {method1: method1,
combine: combine};
}();
// instantiate an object and call its methods
var obj = new ObjBuilder();
console.log(obj.method1());//prints 30
console.log(obj.combine());//prints NaN. WHY???
【问题讨论】:
-
如果你在
method1中记录this然后在combine中调用它,你会看到问题 -
@t.niese It doesn't seem like it -
window。您必须将其称为this.method1()以提供this上下文。
标签: javascript oop scope prototype