简体   繁体   中英

JavaScript - this.update is not a function

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?

This 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 ie "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.com/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);
 },

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.

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