javascript - How can I make sure 'this' refers to the object literal within the object literal? -
here's simple fiddle.
i want make sure this inside obj obj can call a b. i'm using obj in different function, , when put breakpoint inside b, find this window, not obj.
var obj = { a: function() { return 2 }, b: function() { return 5+ this.a() }, } $('#hey').text(obj.b()); obj defined in file used many other classes, wouldn't make sense define either of methods @ site of using obj.
judging @kamil's answer, looks may need pass in a parameter b. in:
var user = obj.b(obj.a); var obj = { a: function() { return 2 }, b: function(func) { return 5 + func() }, } edit following works, it's messy. there more elegant way?
i ended changing
startingsma = this.simple_moving_average(startingsma, period, accessor) to following:
startingsma = (function(startingsma, period, accessor) { return this.simple_moving_average(startingsma, period, accessor) }).apply(statistics, [startingsma, period, accessor]);
i don't know why hasn't been suggested yet - use bind:
var obj = {}; obj.b = (function () { // "this" "obj" }).bind(obj); reference:
Comments
Post a Comment