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.

kevinius
  • 4,232
  • 7
  • 48
  • 79
  • The value of this as well as a lot of other things is explained here: http://stackoverflow.com/questions/16063394/prototypical-inheritance-writing-up/16063711#16063711 – HMR Nov 28 '14 at 00:37

1 Answers1

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

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
  • Can you explain 'why' you need to bind it? – kevinius Nov 27 '14 at 19:24
  • Have a look at the first example from the [MDN docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind): " 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." – Renato Gama Nov 27 '14 at 19:31