Any way to modify 'this' in JavaScript?

后端 未结 4 1433
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 08:56

I found this answer: How to modify "this" in javascript

But I did not like it. Surely there must be a way to somehow modify this?

4条回答
  •  忘掉有多难
    2021-01-06 09:20

    Actually the problem here is that when you binding the function to a number then the this is getting changed to number and now when you are doing the assignment operation this += 5; the left hand side is not a variable where we can store the new value as its a primitive number instance. so to overcome that what you can do is you can store the this value in another variable say me and then do the operation as following:

    (function() {
    
        var a = function(v) {
            v += 10;
    
            a = function() {
                var me = this;
                console.log(this); //logs Number {[[PrimitiveValue]]: 10}
                me += 5; 
                console.log(me); //logs 15
            }.bind(v)
    
            //a();
        }
    
        a(0);
        a();
    
    })();
    

提交回复
热议问题