not sure if this is possible or if I'm doing it wrong. I'm trying to have an object literal reference one of it's own properties that is another object literal. I keep getting an error stating that it is undefined:
var MyObject = {
init: function(){
this.elements.buttons.click(function(){
alert('hit');
});
},
elements: {
buttons: $('button')
}
}
what am i doing wrong?
UPDATE: main.js is calling init to initialize on demand which probably doofed the scope --
function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
$(document).ready(function(){
// invoke init() for any element that requests it
$('[data-page]').each(function(i, p){
var page = 'APP.MODEL.' + $(p).data('page') + '.init';
executeFunctionByName(page, window)
});
});
If you are invoking that function directly without going through MyObject
, this
would be undefined. Replace this
with MyObject
and it should work.
This would not work as this
would be defined to window
:
var MyObject = {
// init: ...
}
var init = MyObject.init;
init();
See 3. Entering function code : How does the "this" keyword work?
If you wish to continue to use this
, you may use Function.prototype.call() or Function.prototype.apply() like so:
var MyObject = {
// init: ...
}
var init = MyObject.init;
init.call(MyObject);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.