简体   繁体   中英

javascript: disable re-writing object methods

Is there any way to disable the rewriting on methods on javascript objects?

For example :

var myObj=new Object();
myObj.doSomething=function(){
 alert("good message")
}

myObj.doSomething=function(){
 alert("bad message")
}

myObj.doSomething(); // I want to alert me with "good message"

I think this can be done , cause I wanted to to rewrite a method a few years ago, and I received an error in javascript console about that method has only get and not set.

Thanks

In ECMAScript 5 you can set objects to be unmodifiable :

Object.freeze(myObj);

You can create an individual property that can't be modified using:

Object.createProperty(myObj, 'name', descriptor);

where descriptor is itself an object containing flags , one of which is configurable which if set to false prevents that property from being changed or deleted.

JavaScript is designed around the notion that anything can be changed. You can override the functionality of just about anything , anywhere , at any time.

This is both a blessing and a curse.

If you ran into that error message, it was likely either (a) a bug in a JavaScript/JScript implementation, or (b) not what you thought it was.

AMMENDED: It's possible you were looking at ECMAScript 5 code. I've been maintaining ECMAScript 3 for so long I've apparently developed cataracts that blind me to that possibility. Forgive me. I stand humbly corrected.

While Alnitak has a nice direct answer to your question, depending on what you are trying to accomplish you may be able to prevent 're-writing' a method by making it a 'private' variable through a closure. It won't protect 'public' functions, but can hide private ones and prevent them from being modified.

var myObj = (function(){
    var data = {count: 0};
    var privateFunction1 = function(){
      data.count++;
    };

    var privateFunction2 = function(){
      // do something else
    };

    var result = {
        callPrivateFunction: function(){
            privateFunction();
            privateFunction2();
        }
    };

    return result;
})();

Of course, any public function that calls the private function is re-writable, so depending on what you're trying to accomplish the may just be pushing the problem around. However, this approach is a nice way to accomplish some encapsulation and not present more in the API of the object than you want.

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