简体   繁体   中英

How can I make “this” refer to the member function and not the instance of its owner class?

function foo(name){
  this.name = name;
  this.bar = function() {
    this.name = "John"
    console.log("bar's name is " + this.name);
  }
}

var blah = new foo("Peter");
console.log(blah.name);//"Peter"
blah.bar();//"bar's name is John"
console.log(blah.name);//"John"

In the example above, how can I make "this", within the function bar, refer to bar, and not its owner, foo? The desired result would be:

var blah = new foo("Peter");
console.log(blah.name);//"Peter"
blah.bar();//"bar's name is John"
console.log(blah.name);//"Peter"

blah.bar();//"bar's name is John"
Here you are simply calling the function bar, if you want bar to be it's own object (and have properties like a name), you need to do:
var bar = new blah.bar();
This will create the output you're expecting.

Your example looks like you do not want to use this at all, but a local variable that is not a property of anything:

function Foo(name) {
  this.name = name;
  this.bar = function bar() {
    var name = "John";
    console.log("the name is " + name);
  }
}

var blah = new Foo("Peter");
console.log(blah.name); // "Peter"
blah.bar();// "the name is John"
console.log(blah.name); // still "Peter"

Notice that the function's .name ( blah.bar.name ) is "bar" (at least in my example, in your code it was empty) just as Foo.name is "Foo" , and you even cannot set it.

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