简体   繁体   中英

jquery extend of prototype

i have some javascript code that i use in my html pages, the .js file looks like this:

(
function(exports){
  var cubism = exports.cubism = {version: "1.3.0"};
  var cubism_id = 0;
  function cubism_identity(d) { return d; }
  ...
}
)(this);

i want to add some new functionality to the base library, so i do the following (sorry in coffeescript):

jQuery.extend cubism.context.prototype,
   "horizon": () ->
       metric = cubism_identity

the problem is when i run the code i get:

Uncaught ReferenceError: cubism_identity is not defined 

how can i access the function cubism_identity() in my extended prototype?

A function is available within the scope it is defined and not at a higher level scope unless it is specifically assigned as a property on a higher level object.

With the way you've written your code, cubism_identity() is a function that is only visible inside the scope of your function(exports){ function body. If you want it available outside that scope, then you will have to either define it at a higher scope where you can then use it or you will have to assign it as a property of some higher level object such as window or your own namespace object.

For example, you could move it to the global scope:

function cubism_identity(d) { return d; }

(
function(exports){
  var cubism = exports.cubism = {version: "1.3.0"};
  var cubism_id = 0;
  ...
}
)(this);

Though, it is generally better to put it on a global namespace object so you don't add more things to the global scope than needed.

Or, conversely, you could define the function that uses it inside the function(exports) body so it can use it right where you originally had it.

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