Restrict method override of an object in javascript

4

I'm trying to create an object where its methods can not be changed. That is, its value, even if changed, should continue as initially defined.

Example:

var object = (function(object){

      object.method = function (text) {
          return 'response ' + text + '!!!';
      }

})({});

I can access it as follows:

object.method()

But you can change the method by simply doing this:

 object.method = null
 //TypeError: object is not a function

In jQuery , when we make this attempt to change, 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') to a variable:

$body = $('body');
$body.html = null;
////TypeError: object is not a function

In the first example used with jQuery , how does it internally do to keep the methods intact? Does it always create a new instance?

How to block rewriting of an object's methods?

    
asked by anonymous 09.02.2015 / 16:11

2 answers

6

You can use Object.defineProperty in order to have greater control over the characteristics of your method (or field). For example, to make your method read-only, assign writable to false :

var object = (function(object){

      Object.defineProperty(object, 'method', {
          value:function (text) {
              return 'response ' + text + '!!!';
          },
          writable:false
      });
  
      return object;

})({});

document.getElementById("saida").innerHTML += object.method("teste") + "<br>";

// Não tem nenhum efeito (mas não lança nenhuma exceção!)
object.method = function() {
    return "Tentando mudar o método";
};

// Ainda chama o método antigo
document.getElementById("saida").innerHTML += object.method("teste");
<p id="saida"></p>

P.S. The jQuery case you mentioned behaves this way because the object returned by $(...) is not the same in one invocation and another:

var a = $('body');
var b = $('body');
a == b; // false

In addition, if you override a method with $.fn it becomes valid for all objects created from $(...) :

$.fn.html = function() {
    alert("Método alterado!");
};

$('body').html(); // Chama o método sobrescrito
    
09.02.2015 / 16:25
0

Because when you do:

$('body').html = null
$('body').html()

You are calling the $ function separately so it will always return a separate object.

    
09.02.2015 / 16:15