开发者

Referencing functions from within functions inside a JavaScript object

var Page = {
    data: null,
    Load: function () {
        this.Populate;
    },
    Populate: function () {
    }
};

$(document).ready(Page.Load);
  1. Why can't I reference Page.Load as a function in ready() eg .ready(Page.Load())
  2. Why can't I call this.Populate() fro开发者_高级运维m the Load function, I just get this.Populate() is not a function.


Why can't I reference Page.Load as a function in ready() eg .ready(Page.Load())

Sticking () on the end calls a function. You want to pass the function itself, not its return value. (The ready function will call what you pass to it later).

Why can't I call this.Populate() from the Load function, I just get this.Populate() is not a function

Two reasons.

First, you never actually call the Populate function. Change to:

this.Populate()

Second: because you detach the Load function from the object, so this isn't Page by the time it gets called.

Do this instead:

$(document).ready(function () { Page.Load() });


There are two problems in your code.

First, as Rob says, you're not actually calling the Populate() method in Load(). You need to add parenthesis to do that.

Second, the this keyword in Populate() does not refer to the Page object. You can use $.proxy() to set the Page object as the context of the method call:

var Page = {
    data: null,
    Load: function() {
        this.Populate();
    },
    Populate: function() {
    }
};

$(document).ready($.proxy(Page.Load, Page));


A function call should be in the format function_name() (parentheses!). A function reference should be function_name (without parentheses). This code will work:

var Page = {
    data: null,
    Load: function () {
        Page.Populate(); //PARENTHESES
    },
    Populate: function () {
    }
};

$(document).ready(Page.Load);//NO PARENTHESES

$(document).ready is a function which expects a function to be parameter 1. If you use Page.Load(), you will execute function Page.Load() and pass the return value (undefined, in this case) to $(document).ready.


You can get it to work by wrapping your object up in a function like this:

var Page = (function () {
    var that = {
        data: null,
        Load: function () {
            that.Populate(); 
        },
        Populate: function () {
            alert("Test");
        }
    };
    return that;
})(); // Execute the function immediately to return 'that'

$(document).ready(Page.Load);

This way you can call between methods as you have a reference to the object (that).

JSBin Example


You're calling the function Page.Load. But more specifically you're calling the function that Page.Load is set to (since that argument to .ready() is just a simple value); you're not calling it on Page, so 'this' is not reset to point to the Page object.

This will work better:

$(document).ready(function() {
    Page.Load();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜