开发者

How best to overwrite a Javascript object method

I'm using a framework that allows the include of JS files. At the top of my JS file I have something like:

<import resource="classpath:/templates/webscripts/org/mycompany/projects/library/utils.lib.js">

I want to override a fairly small method that is defined in the very large utils.lib.js file. Rather than make the change directly in utils.lib.js, a file that's part of the framework, I want to overwrite just one method. The utils.lib.js file has something that looks like:

var Evaluator =
{
   /**
    * Data evaluator
    */
    getData: function Evaluator_getData(input)
    {
          var ans;

          return ans;
    },
    ...
 }

I want to change just what the method getData does. Sorry for the basic question, but after importing the file which copies the JS contents into the top of my JS file, can I just do something like:

 Evaluator.getData 开发者_运维问答= function Mine_getData(input)
                {
                  ...
                };


Yes, you can just reassign that method to your own function as you have proposed with:

 Evaluator.getData = function Mine_getData(input)
 {
     ...
 };

This will successfully change what happens when the .getData(input) property is called.


Yes you can.

However Evaluator is not a proper 'class'. You can't write var x = new Evaluator(); So you are not overriding, but just changing the variable getData. That's why we say that in JavaScript, functions are first-class citizen, treated like any variable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜