node.js - Given that JavaScript has closures, what exactly is the purpose of the this keyword? -
given following code, can see closures contain value of variables inside scope:
var f = new foo('jim','jam'); var b = new bar('saul','paul'); var bz = new baz(); function foo(jim,jam){ this.jim = jim; this.jam = jam; function log(){ console.log('jim:',jim,'jam:',jam); } return log; } function bar(jim,jam){ function log(){ console.log('jim:',jim,'jam:',jam); } return log; } function baz(jim,jam){ this.jim = 'bark'; this.jam = 'catch'; function log(){ console.log('jim:',this.jim,'jam:',this.jam); } return log; } f(); b(); bz();
so, purpose of 'this
' keyword in javascript then? when become necessary?
the this
keyword used access current context, not same current scope.
if call method of object, context call object. can use this
keyword access properties in object:
function foo(jim,jam){ this.x = jim; this.y = jam; } foo.prototype.log = function(){ document.write('jim:' + this.x + ', jam:' + this.y); }; var f = new foo('jim','jam'); f.log();
Comments
Post a Comment