Assign object to “this”

后端 未结 4 617
余生分开走
余生分开走 2020-12-07 02:30

Say I have a class and some static helper methods like this:

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

    this.replaceMe = function (value) {
             


        
4条回答
  •  隐瞒了意图╮
    2020-12-07 03:15

    I wanted to do something very similar a while back. Unfortunately there's no way to assign a value to this - the this pointer is a read only variable. However the next best thing is to use a getter and setter object to change the variable holding your instance itself.

    Note that this only updates a single reference to the instance. You can read more about it here: Is there a better way to simulate pointers in JavaScript?

    So this is how it works:

    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);
    };
    

    This is how to create the pointer and use it:

    var instance = new MyClass({
        get value() { return instance; },
        set value(newValue) { instance = newValue; }
    }, 2);
    
    instance.revealVar();               // alerts 2
    instance.replaceMe(40).revealVar(); // alerts 42
    

    It's not the most elegant solution but it gets the job done. You can see this code in action: http://jsfiddle.net/fpxXL/1/

提交回复
热议问题