2

say I have this:

function something() {
    //does something here
}
something.prototype = {
    xy: function(n) {
        this.a = n;
    }
    y: function() {
        b = this.xy(n);
    }
}

my qusetion is, I know that in this.a, this refers to something. However, is b=this.xy(n) allowed, and if so, what would this in b=this.xy(n) refer to?

kay
  • 23,543
  • 10
  • 89
  • 128
slynthin
  • 65
  • 3
  • *"what would this in b=this.xy(n) refer to"* That entirely depends on *how you call* `something.prototype.y`. Please read the documentation about `this`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – Felix Kling Aug 16 '14 at 02:59

3 Answers3

1

In this.a, this does not refer to something. You could expect it to refer to an instance of something, but this can be bound to anything using Function.prototype.call or Function.prototype.apply. If you call foo.y() in the same way you call foo.xy(), though, it will refer to foo and that usage will be valid, yes. More than that, this would be the correct way to do it, to allow anything inheriting from something to override xy.

Ry-
  • 199,309
  • 51
  • 404
  • 420
1

the actual reference for "this" is not always the same and changes depending on the context and how you call the function.

for e.g lets assume you have got a global variable "a"

var a;    
...
something.prototype = {
    xy: function(n) {
        this.a = n;
    }
    ...
}

var obj = new something();
obj.xy.call(this, 10); // set the context to global. this == 'global' here

console.log(obj.a); //undefined
console.log(a); //10

the above code calls the xy function, but sets "this" to the global object and modifies the global variable a instead of the instance variable. "this" inside the function does not refer to the object instance but the global object (window object).call and apply can be used to modify the actual meaning of "this", whenever functions are called.

obj.xy(10);
console.log(obj.a); // 10

here you are setting the context to the object instance and "this" refers to the object instance correctly and you get the expected output.

And to answer your question

is b=this.xy(n) allowed, and if so, what would this in b=this.xy(n)

this is allowed and the result would be again depending on the context of the call that you are making.

Prabhu Murthy
  • 8,614
  • 5
  • 26
  • 34
-1

Ok, I assume you function is a constructor, the I create a object:

var obj = new something(). 

"this" keyword then refer to obj. you can do:

obj.y();

then obj.a will be set to value n. I think that's what you plan to do..

Also, your xy function doesnt have return statment,there is nothing assign to b.