I dont understand one thing:
var comein = document.getElementById("comein");
var enter = new Expand({ elem : comein });
function Expand (options) {
this._elem = options.elem;
console.log(this._elem); // i have a div element
}
Expand.prototype = {
check : function () {
var comInClassName = this._elem.className; // i have an error: this._elem is undefined
if (comInClassName == "open"){
this.close();
}
if (comInClassName == "close"){
this.open();
}
}
}
log_in.addEventListener("click", enter.check, false);
Why I have an error in prototype method if in Expand i have a normal element? Thanks
It depends entirely on how you call
check. If you call it like this:….then within the call,
thiswill refer to theenterobject and it will have an_elemproperty. If, on the other hand, you set it up to be called like this:…then within the call (when the event occurs),
thiswill not refer toenter, but rather tothis._elem, and so it has no_elemproperty.This happens because in JavaScript (for now),
thiswithin a function call is defined entirely by how the function is called, not where the function is defined. If you call it as part of an expression retrieving the function reference from an object:…then
thisrefers to the object you got the function reference from. But if you call it separately, as with theaddEventListenercall above, it doesn’t.If you’re on an ECMAScript5-enabled environment (or if you have a decent ES5 shim in place), you can fix that by using
Function#bind:bindreturns a function that, when called, will turn around and call the underlying function using the giventhisvalue (enter, in our case).More to explore (on my blog):
this