Assign this object

Let's say I have a class and some static helper methods like this:

function MyClass (myVar) {
    this.myVar = myVar;

    this.replaceMe = function (value) {
        // this will fail
        this = MyClass.staticHelper( value );

        return this;
    }

    this.revealVar = function () {
        alert( this.myVar );
    }
}

MyClass.staticHelper = function (instance, value) {
    return new MyClass( instance.myVar + value );
}

I want to do something like this:

var instance = new MyClass( 2 );

instance.revealVar(); // alerts 2
instance.replaceMe( 40 ).revealVar(); // alerts 42

The reason is that my class has a slightly more complex structure, and I do not want to assign all the internal variables manually each time, but rather replace the entire object. Is there an easy way to do this?

+5
source share
4 answers

instance.replaceMe( 40 ).revealVar(); warnings 42

OK, that return MyClass.staticHelper(this, value);’s enough for that . The only question is whether the next call should instance.revealVar()now warn 2 or 42 - if you want it to instancebe changed to 42, it becomes more complicated:

this = MyClass.staticHelper( value ); // this will fail

... this , ThisBinding , , - , .

, .

, , instance ( ), instance revealVar() 2.

?

, . - call () , new :

MyClass.call( instance, instance.myVar + value );

, . , replaceMe this, replaceMe.

, , , :

….replaceMe = function(val) {
    var newInst = MyClass.staticHelper(this, val); // new MyClass(this.myVar+val);
    for (var prop in newInst)
        if (newInst.hasOwnProperty(prop))
            this[prop] = newInst[prop];
    return this;
};

, , .

Btw, , .

+1

:

function MyClass(myVar) {
    // ...

    this.replaceMe = function (value) {
        return MyClass.staticHelper(this, value);
    }

    // ...
}

MyClass.staticHelper = function (instance, value) {
    return new MyClass( instance.myVar += value );
}
0

, Javascript.

-, , , this * . this=foo bar()=baz. :

a = 5
a.change(10)
alert(a == 10) // nope

-, this=z , , Javascript , , :

a = 5
change(a)
alert(a == 10) // nope

* "" " "

0

- . , this - this . getter setter , .

, . : JavaScript?

:

function MyClass(pointer, myVar) {
    this.myVar = myVar;

    this.replaceMe = function (value) {
        pointer.value = MyClass.staticHelper(this, pointer, value);
        return pointer.value;
    };

    this.revealVar = function () {
        alert(this.myVar);
    };
}

MyClass.staticHelper = function (instance, pointer, value) {
    return new MyClass(pointer, instance.myVar + value);
};

pointer :

var instance = new MyClass({
    get value() { return instance; },
    set value(newValue) { instance = newValue; }
}, 2);

instance.revealVar();               // alerts 2
instance.replaceMe(40).revealVar(); // alerts 42

, . : http://jsfiddle.net/fpxXL/1/

0

All Articles