0

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.

1

1 Answer 1

2

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."

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain 'why' you need to bind it?
Have a look at the first example from the MDN docs: " A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its this (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.