admin管理员组文章数量:1335607
Recently i tried to use JavaScript OOP with jQuery, I wrote this code:
var beer = function(){};
$.extend(ntf.prototype, {
types:{
'.test':'test',
},
init:function() {
$.each(this.types, function(key, value) {
this.update(key, value);
});
},
update:function(className, actionName) {
$(className + ' .event').click(function() {
$(this).parent().find('.pevent').load('navigate.php?do=create&action=' + actionName);
alert("TEST");
}).click();
},
pics:{
add:function(element) {
$.post("navigate.php?do=nav&action=pics", {
name:$(element).data('name'),
});
}
}
});
beer.prototype.init();
But, in the console it return this error: Uncaught TypeError: this.update is not a function
.
How can i use JavaScript OOP with jQuery in better way, And how can i solve this problem?
Recently i tried to use JavaScript OOP with jQuery, I wrote this code:
var beer = function(){};
$.extend(ntf.prototype, {
types:{
'.test':'test',
},
init:function() {
$.each(this.types, function(key, value) {
this.update(key, value);
});
},
update:function(className, actionName) {
$(className + ' .event').click(function() {
$(this).parent().find('.pevent').load('navigate.php?do=create&action=' + actionName);
alert("TEST");
}).click();
},
pics:{
add:function(element) {
$.post("navigate.php?do=nav&action=pics", {
name:$(element).data('name'),
});
}
}
});
beer.prototype.init();
But, in the console it return this error: Uncaught TypeError: this.update is not a function
.
How can i use JavaScript OOP with jQuery in better way, And how can i solve this problem?
Share Improve this question edited Jul 18, 2016 at 23:28 asked Jul 18, 2016 at 23:22 user6184150user61841502 Answers
Reset to default 3This is the scope issue. Please notice that "this" is different before the "each" function call and inside the call.
You can use the scope by assigning it to a local variable i.e. "me" in this case.
init:function() {
var me = this;
$.each(this.types, function(key, value) {
me.update(key, value);
});
},
And if you want to see what is the difference between the scopes, just log both and check in the console.
Here first "this" is the global scope whereas the second one (inside the anonymous method) is the local scope.
init:function() {
console.log(this);
$.each(this.types, function(key, value) {
console.log(this);
});
},
You can refer this for more clarification on scope of this : http://javascriptplayground./blog/2012/04/javascript-variable-scope-this/
In addition to what @Ash said, I am a fan of bind
init:function() {
$.each(this.types, function(key, value) {
this.update(key, value);
}.bind(this);
},
本文标签: jqueryJavaScriptthisupdate is not a functionStack Overflow
版权声明:本文标题:jquery - JavaScript - this.update is not a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742373352a2462670.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论