2

Check my code below, I am just lost here why am I getting this error. Any suggestion please. Here I have made a class test and added two methods check and nextfn. I am calling check from nextfn.

var test=function(){}

test.prototype.check=function()
{
  console.log("hello from checking");
}

test.prototype.nextFn=function(){

  check();

  console.log("Hello from nextfn");
}

Next

var t=new test();
t.nextfn();

The error is

Uncaught ReferenceError: check is not defined(…)

Now consider another scenario;

test.prototype.anotherFn=function()
{
    var p=new Promise(function(){
         this.check();
    })
}

Now also getting same error;

Uncaught ReferenceError: check is not defined(…)

When calling

var t=new test();
t.anotherFn();
3
  • 4
    this.check(); Commented Feb 8, 2017 at 14:12
  • 2
    Also, new test() instead of new text() Commented Feb 8, 2017 at 14:14
  • to expand on @Igor comment, the check method was put on the prototype of test. nextFn is part of the same prototype, this is a keyword referring to the parent/prototype. Commented Feb 8, 2017 at 14:16

1 Answer 1

6

The check function is on the prototype of the test object.

When you invoke nextFn like this:

t.nextfn();

The ensuing scope will be bound to the t instance of "type" test. Access within nextfn to test's prototype will be available via this.

So access check using this:

this.check();

This stuff can get surprisingly confusing. A good reference is this book.

====

For your second scenerio, the problem is that you are trying to invoke this from within a function that has it's own scope.

Scope in JavaScript is generally not block scoped, but rather function scoped. There is a lot more to it, and I would recommend reading a tutorial on closures to get a more rounded description, but for now, try this instead:

test.prototype.anotherFn=function()
{
    var self = this; // save reference to current scope
    var p=new Promise(function(){
         self.check(); // use self rather than this
    })
}
Sign up to request clarification or add additional context in comments.

2 Comments

Worked well, now added another scenario in my question; can you please clarify this one also please. I understand that it is now going to the scope of p. But how to call the function check then?
@KOUSIKMANDAL I updated my answer for the second part of the question

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.