0
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"
michaelAdam
  • 1,119
  • 14
  • 30
  • Why would you ever want `this` to refer to a function? Especially since [that wouldn't work any more](http://stackoverflow.com/q/18904399/1048572)? – Bergi Oct 11 '14 at 16:05
  • Afaik, the name property of a function is readonly, so even if you set `this` to the function itself, it wouldn't work. Anyway, this is how you bind `this`: `this.bar = this.bar.bind(this.bar);`. However, I don't see a reason you'd ever want to do that. – Felix Kling Oct 11 '14 at 16:25

2 Answers2

0

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.

orhanhenrik
  • 1,407
  • 8
  • 11
0

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375