简体   繁体   中英

Value of “this” in a JS constructor function returns “undefined”

So i have a constructor function

    var APP = function(name){

        this.appName = name

    }

And a prototype function

    APP.prototype.test = function(){

        console.log(this.appName)

    }

Then i create a new APP() and try out the test function.

    var app = new APP("ieps")
    var testing = app.test

    console.log(app.test()) // returns "ieps"
    console.log(testing()) // returns undefined

Why is it that testing() is returning undefined? testing() should do the same thing as app.test() since i'm just referencing app.test.

You would have to bind the object to the function

var app = new APP("ieps");
var testing = app.test.bind(app);

console.log(testing());

http://jsbin.com/kiyiyutili/2/edit

EDIT: From the MDN docs for .bind :

"The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM