开发者

jQuery: NewBie Questions, how to call function from another class in jquery?

开发者 https://www.devze.com 2022-12-26 18:53 出处:网络
I have function getCartItems in cart.js and I want t开发者_开发技巧o call that function in another class checkout.js than how can I do this ?You need to include the script file cart.js in your page be

I have function getCartItems in cart.js and I want t开发者_开发技巧o call that function in another class checkout.js than how can I do this ?


You need to include the script file cart.js in your page before you include checkout.js. Assuming the function getCartItems is declared in the global namespace, that's all you have to do.

However, don't confuse a Javascipt source file for a class. Javascript does not have classes in that sense.


I hate to throw a more complicated answer in here but one thing you can do to help simplify things is to use pseudo namespaces. Here is an example:

// In cart.js
var CartNS = {};
CartNS.getCartItems = function(){
    function text here...
}

// In checkout.js
CartNS.getCartItems();

By organizing things into namespaces it can make it easier to deal with scope issues (one of the most difficult concepts in JavaScript) and it makes it a little easier to find things as well. This is also a way to simulate Classes in JavaScript. A decent example to get you started is: 3 ways to define a JavaScript class

0

精彩评论

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