, , this invoking object.
window.sayHi=function(){
console.log(this.name);
}
window.name="Window"
window.sayHi();
var obj={
name:"obj"
}
obj.fn=window.sayHi;
obj.fn();
, this . , closure call, apply bind:
obj.fn=(function(w){
return function(){
w.sayHi();
}
}(window));
obj.fn();
obj.fn.call(window);
obj.fn.apply(window);
var boundFn=obj.fn.bind(window);
boundFn();
, . , this , .
, :
var obj={
name:"obj"
}
var Test=function(){
this.name="Test";
}
Test.prototype.sayHi=function(){
console.log(this.name);
};
var t=new Test();
obj.fn=t.sayHi
t.sayHi();
obj.fn();
, setTimeout :
someButton.onclick=t.sayHi;//when button is clicked this will be the button clicked
setTimeout(t.sayHi,100);//when sayHi is executed 'this' will be window
To answer your question about obj1 existing in the body of the constructor function; I would say no (not in Firefox, at least). I have no reference to the specifications, but obj1 will matter thiswhen the constructor function returns:
delete window.t;
var Test=function(){
this.name="Test";
console.log("and window.t is:",window.t);
}
Test.prototype.sayHi=function(){
console.log(this.name);
};
window.t=new Test();
Read more about constructor functions, prototype, inheritance, overriding and calling super here .
source
share