Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - How to function call using 'this' inside forEach loop

In the following object, I have a problem using the 'this' reference:

function SampleObject(){
    this.addObject = function(object){...}
    ...
    // more code here
    ...
    this.addNewObjects= function(arr){
        arr.forEach( function (obj) {
            this.addObject(new Obj(obj.prop1, obj.prop2));
        });
    }
}

I'm assuming the context is changing and that 'this' refers the iterated 'obj', and not 'SampleObject'. I've solved the problem using a normal for loop however, i'm curuois to why this is not working, and would like to know if there is another way to do this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can store this in variable:

var self = this;
this.addNewObjects = function(arr){
    arr.forEach(function(obj) {
        self.addObject(new Obj(obj.prop1, obj.prop2));
    });
}

or use bind:

this.addNewObjects = function(arr) {
    arr.forEach(function(obj) {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    }.bind(this));
}

And side note, without those this will be window object not obj. This is always object that was created using new keyword or window object if it's normal function. In strict mode this will be undefined in this case.

UPDATE: and with ES6 you can use arrow function:

this.addNewObjects = function(arr) {
    arr.forEach((obj) => {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    });
}

arrow functions don't have their own this and they get it from outer scope.

UPDATE2: from @viery365 comment you can use this as second argument to forEach and it will make context for the function:

this.addNewObjects = function(arr) {
    arr.forEach(function(obj) {
        this.addObject(new Obj(obj.prop1, obj.prop2));
    }, this);
}

You can read this on MDN forEach page


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...