Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object.freeze on object method only. JavaScript

I'm wondering if there is a known way for freezing a method on an object in JavaScript. e.g.

var obj = {};
    obj.method = function(){};
    Object.freeze(obj.method);

Then obj.method = function(){//New function}; wouldn't do anything.

Maybe this doesn't work because it's, strictly speaking, a function but was just wondering if anyone had any solutions that might do what I want.

Also, I am aware of the deepFreeze concept but am trying to avoid using that and adding a where clause to only freeze that object due to the fact that my object is actually very big so I don't want to loop through it.

Thanks.

like image 924
rygo18 Avatar asked Feb 12 '26 03:02

rygo18


1 Answers

Then obj.method = function(){//New function}; wouldn't do anything.

Yes, it's quite simple with Object.defineProperty.

Object.defineProperty(obj, 'method', {
   value: function() {/* ... */},
   enumerable: true, // will show in Object.keys and for..in loop
   configurable: false, // can't be deleted
   writable: false // can't be redefined
});
like image 113
Ginden Avatar answered Feb 13 '26 17:02

Ginden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!