'这'附加到原型的对象的getter和setter函数的绑定

时间:2015-02-25 12:56:13

标签: javascript prototype

给出以下代码:

function Constructor(){}

var proto = Constructor.prototype;

proto.someMethod = function(){};
proto.someProperty = "some value";

proto.obj = {};

Object.defineProperty(proto.obj, "prop", {
    get: function() {
            return this.someMethod() + this.someValue;   
        }
});

var instance = new Constructor();
instance.obj.prop; // => Uncaught TypeError: undefined is not a function

用作getter或setter的函数将'this'值绑定到正在设置或获取属性的对象。代码中getter函数的'this'值指向'proto.obj'。有没有办法将getter函数的'this'值绑定到'Constructor'的实例,以便能够访问属性和方法?

0 个答案:

没有答案
相关问题