rygo18
rygo18

Reputation: 153

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.

Upvotes: 3

Views: 269

Answers (1)

Ginden
Ginden

Reputation: 5316

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
});

Upvotes: 3

Related Questions