最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object function is not a function - Stack Overflow

programmeradmin0浏览0评论
var plugin = {
    Init: function() {
        this.UpdateUI();
        if (this.Status() == 1) {
            ...
        } else {
            ...
        }
    },
    Status: function() {
        ...
    },
    UpdateUI: function() {
        ...
    }
}

This is the basic code. The problem is, when Init is called, the following errors appear:

this.UpdateUI is not a function
this.Status is not a function

Can someone tell me what's the problem with my code?

var plugin = {
    Init: function() {
        this.UpdateUI();
        if (this.Status() == 1) {
            ...
        } else {
            ...
        }
    },
    Status: function() {
        ...
    },
    UpdateUI: function() {
        ...
    }
}

This is the basic code. The problem is, when Init is called, the following errors appear:

this.UpdateUI is not a function
this.Status is not a function

Can someone tell me what's the problem with my code?

Share Improve this question asked Jan 9, 2012 at 19:23 BogdacutuBogdacutu 7717 silver badges24 bronze badges 4
  • 2 Can you post the code that calls Init()? – Frédéric Hamidi Commented Jan 9, 2012 at 19:26
  • scoping issues, this isn't referring to plugin, it's referring to the init function. If you placed the Status and UpdateUI functions within the init function, then your code would work correctly. I think bardiir has the correct solution for you. – Cory Danielson Commented Jan 9, 2012 at 19:32
  • I think we just found one of the ugly sides of javascript and according to the votes on my answer there seem to be some differenting viewpoints about this :D – bardiir Commented Jan 9, 2012 at 19:40
  • 1 @CoryDanielson: We don't know what this refers to because we don't know how Init is being called. But it isn't a scoping issue, and merely placing the functions inside the Init function will not work. – user1106925 Commented Jan 9, 2012 at 19:42
Add a ment  | 

2 Answers 2

Reset to default 4

That's because this inside plugin.Init refers to plugin.Init and not to plugin itself. Change it like this:

var plugin = {
    Init: function() {
        plugin.UpdateUI();
        if (plugin.Status() == 1) {
            ...
        } else {
            ...
        }
    },
    Status: function() {
        ...
    },
    UpdateUI: function() {
        ...
    }
}

Prototyped:

function Plugin(){
  var self = this;

  this.Init = function() {
    self.UpdateUI();
    if (self.Status() == 1) {
      ...
    } else {
      ...
    }
  };
}

Plugin.prototype.status = function() {
            ...
  };
Plugin.prototype.UpdateUI: function() {
    ...
  }

var plugin = new Plugin();

In the Context where init is called this might be something else.

Try to use plugin.UpdateUI and plugin.Status instead, that always references the correct functions.

发布评论

评论列表(0)

  1. 暂无评论