-1

I have this script:

Bla = function() {
  this.prop = 123;
}
Bla.prototype.yay = function() {
  console.log(this,this.prop);
}
X = new Bla();

$(document).ready(X.yay); // output: #document undefined --> why?
$(document).ready(function(){
  X.yay(); // output: Bla 123 --> desired result
});

How to make the first one calls correctly (this should refer to X) without extending Object ?

Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • What do you mean, "*without extending `Object`*"? – Bergi Dec 10 '14 at 04:41
  • without adding `Object.prototype.bla` – Kokizzu Dec 10 '14 at 04:46
  • Uh, I don't think there even is a working solution that uses `Object.prototype`… – Bergi Dec 10 '14 at 04:48
  • If I'm not forgotten, there is `Object.prototype.bind` from `ImpactJS` library (I ask because I forgot the `bind` function's name) – Kokizzu Dec 10 '14 at 05:21
  • I've never heard of ImpactJS, but what you remember is the [`Function.prototype.bind` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) - that is native and does not need any extensions on `Object`. – Bergi Dec 10 '14 at 05:26
  • ah yeah, that one http://impactjs.com/forums/impact-engine/bug-in-function-bind – Kokizzu Dec 10 '14 at 05:27

2 Answers2

1

Short answer, no matter where a function is called, this refers to object it is a property of, or the global object is not a property of an object.

When you pass the method into a function, that function is no longer a method of an object, but a local variable to the function, in which, in this case anyway, this refers to the document object, since that is the object the document ready event is called on.

In modern JavaScript implementations, you can bind the method to the object.

Example:

$(document).ready(X.yay.bind(X));

Note that this requires IE9 or better. The anonymous function you use is also an acceptable solution, and will work in older versions of IE.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
1

You can use bind:

$(document).ready(X.yay.bind(X));

This creates a "wrapper" around the function that sets this to X when it is invoked.

Thilo
  • 257,207
  • 101
  • 511
  • 656