javascript - Local Instance Reference -
in javascript have:
var person = (function () { function person(data) { info = $.extend({ name: "", age: 0 }, data); this.name = data.name; this.age = data.age; } homecoming person; })(); person.prototype.getname = function () { homecoming this.name; };
...if understand 'this' keyword correctly in javascript, can refer pretty much window object in-between (e.g. callers of object). question how heck write methods .getname() know i'll have reference value stored in person object's name property if never can sure 'this' refer in method? .getname() called , 'this' references window object - how value need then?
i'm asking because i've inherited code using pretty heavy prototyping , i'm running kinds of issues trying reference properties , methods on objects within themselves. seems i'm missing i've been looking scope, closures, , other patterns day , can't around this.
the value of this
set language according how function/method called.
if have object method , do:
obj.method()
then, this
set point object within of method()
function.
but, if method this:
var p = obj.method; p();
then, because there no object reference in actual function call, this
set either window
or undefined
depending upon whether in strict mode or not.
additionally, caller can specify want this
set using obj.method.call()
or obj.method.apply()
or p.call()
or p.apply()
previous example. can these methods on mdn see more details how work.
so, in previous code, should work:
function person(data) { info = $.extend({ name: "", age: 0 }, data); this.name = data.name; this.age = data.age; } person.prototype.getname = function () { homecoming this.name; }; var p = new person({name:"john"}); var n = p.getname(); // homecoming "john"
working demo: http://jsfiddle.net/jfriend00/a7mkp/
if needed pass getname()
3rd party library won't phone call object context, there few options this:
anonymous function:
var myperson = new person("john"); callthirdparty(function() { // callback calls getname right object context homecoming myperson.getname(); });
using .bind()
(not suported in older browsers):
var myperson = new person("john"); var boundfn = myperson.getname.bind(myperson); callthirdparty(boundfn);
from own method:
var self = this; callthirdparty(function() { // callback calls getname right object context homecoming self.getname(); });
fyi, there no reason self-executing function have surrounding person
constructor function. makes code more complicated , adds no value in case.
javascript design-patterns
No comments:
Post a Comment