开发者

Is anything wrong with my JavaScript format?

I'm on a .NET MVC2 project and have a reference to SomeClass.Home.js and jQuery in the masterpage. My SomeClass.Home.js looks like this:

SomeClass.Home = {};

$(document).ready(function () {
    SomeClass.Home.SomeMethod();    
});

SomeClass.Home.SomeMethod= function () {
    alert("hello");
};

The call to SomeClass.Home.SomeMethod doesn't work (I don't get the alert). However, if I change it to this, it works, and I 开发者_StackOverflow社区get the alert:

$(document).ready(function () {
    SomeMethod();    
});

function SomeMethod () {
    alert("hello");
};

Is anything wrong with the syntax of the first one?


The problem seems to be in the way you described the SomeClass variable. The following code works for me.

var SomeClass = {};
SomeClass.Home = {};
SomeClass.Home.SomeMethod = function() {
  alert("hello");
};

$(document).ready(function () {
    SomeClass.Home.SomeMethod();    
});


Yes, because you're not declaring the method. I believe you should do it like this:

SomeClass.Home = {
   SomeMethod = function(){ //stuff });
}

$(function(){ SomeClass.Home.SomeMethod() });


What if you embed the function in the class?

SomeClass.Home = {
  SomeMethod= function () {
    alert("hello");
  };
};

$(document).ready(function () {
    SomeClass.Home.SomeMethod();    
});

SomeClass.Home.SomeMethod= function () {
    alert("hello");
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜