简体   繁体   English

JavaScript - this.update不是一个函数

[英]JavaScript - this.update is not a function

Recently i tried to use JavaScript OOP with jQuery, I wrote this code: 最近我尝试使用JavaScript OOP和jQuery,我写了这段代码:

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 . 但是,在控制台中它返回此错误: 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? 我如何以更好的方式使用JavaScript OOP和jQuery,我该如何解决这个问题?

This is the scope issue. 这是范围问题。 Please notice that "this" is different before the "each" function call and inside the call. 请注意,“this”在“each”函数调用之前和调用内部是不同的。

You can use the scope by assigning it to a local variable ie "me" in this case. 您可以通过将范围分配给本地变量(即“me”)来使用范围。

 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. 这里第一个“this”是全局范围,而第二个(在匿名方法内)是本地范围。

 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.com/blog/2012/04/javascript-variable-scope-this/ 您可以参考此内容以获得有关此范围的更多说明: http//javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

In addition to what @Ash said, I am a fan of bind 除了@Ash所说的,我是bind的粉丝

 init:function() {
   $.each(this.types, function(key, value) {
     this.update(key, value);
   }.bind(this);
 },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM