JavaScript - object's functions referencing it

2019-06-11 07:00发布

Here is a (very) simplified version of my code:

    function Ctor() {
        this.i = 0;

        this.increment = function() { this.i++; },
        this.decrement = function() { this.i--; },

        this.display = function() { alert(this.i); }
    };

The problem is, when the code is run, under some circumstances this now points to something else. I do more or less understand that this changes context from one function to another, but I though my increment function (and the others) would, by the magic of closures, "remember" what this is supposed to be.

I tried just eliminating this altogether, and simply referencing i in the functions. That failed also.

What should these functions look like?

2条回答
三岁会撩人
2楼-- · 2019-06-11 07:40

You can not rely on what's in this in JavaScript. More on this topic.

I see you probably want to introduce private attributes like in OOP languages. John Resig described this issue very well.

function Field(val){
    var value = val;

    this.getValue = function(){
        return value;
    };

    this.setValue = function(val){
        value = val;
    };
}

var field = new Field("test");
field.value
// => undefined
field.setValue("test2")
field.getValue()
// => "test2" 

JavaScript works a lot differently than conventional languages like Java, C++ or PHP. But you can get used to it :)

查看更多
女痞
3楼-- · 2019-06-11 07:49

In the instances where this changes, you can do this:

function() { obj.display(); }

Example:

var obj = new Ctor();

function foo(fn) {
    fn();
}

foo(function() {
    obj.display();
});

An alternative is to modify foo() to accept the context to execute the function with, like this:

function foo(fn, context) {
    fn.call(context);
}
查看更多
登录 后发表回答