4
I’m trying to create an object where your methods can’t be changed. That is, its value, even if modified, should continue as originally defined.
Example:
var object = (function(object){
object.method = function (text) {
return 'response ' + text + '!!!';
}
})({});
I can access it as follows:
object.method()
But it is possible to change the method by simply doing this:
object.method = null
//TypeError: object is not a function
Already in the jQuery
, when we make this change attempt, the html method continues to do the same thing for which it was designed.
$('body').html = null
$('body').html() // funciona normalmente
Unless you save the value of $('body')
in a variable:
$body = $('body');
$body.html = null;
////TypeError: object is not a function
In the first example used with jQuery
, how does it internally keep the methods intact? It always creates a new instance?
How to block the rewriting of an object’s methods?
Restricting has no way, because jQuery does not protect anything, you can still do what you want with pure JS. If you use the resource right, it helps you not to screw up. What you can do is create ways to help you don’t screw up, but if you want, you can.
– Maniero
@Bignow, I remembered a guy named
Object.freeze
. Did he solve the problem?– Wallace Maxters
For what you are saying, no. It only prevents the structure of the object from being modified. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
– Maniero
Object.freeze
andObject.seal
are options that ECMA5 makes possible, but there are alternatives. I will take a look here later to see what has already been said. Good question.– Sergio
I gave an answer, but from the comments above I think I may have misunderstood the question... Do you want to know how to prevent an object’s property/method from being changed, or do you want to know how jQuery works? I left a note about it at the end of my reply, but if you want I can elaborate more...
– mgibsonbr
@mgibsonbr I just know that someone got it wrong, who I wouldn’t risk :) Anyway the answer is good.
– Maniero