How to remove a function from the constructor?

How to remove a function from the constructor?

If there is a function called greet in the constructor of Person , how to remove the function?

 function Person(name) { this.name = name; this.greet = function greet() { alert("Hello, " + this.name + "."); }; } 

I want the result to be:

 function Person(name) { this.name = name; } 
+4
source share
2 answers

You cannot change the source of a function. If you want to change the behavior of this function, you have options:

Override the function with your own. It is easy if the function is autonomous. Then you can simply define

 function Person(name) { this.name = name; } 

after determining the original function. But if prototypes and inheritance are involved, it can be difficult to get a link to the original prototype (due to how function declarations are evaluated).

Set up a wrapper function that creates and creates instances and removes properties you don't need:

 function PersonWrapper(name) { var p = new Person(name); delete p.greet; return p; } 

This approach is also limited as you can only change what is accessible from the outside. In the above example, it would be enough for you.

+2
source
 delete this.greet 

or

 var personInstance = new Person(); delete personInstance.greet // to remove it from the instance from the outside 

or

 delete Person.prototype.greet // if doing prototypes and inheritance 

delete is a keyword that you rarely see, but I assure you that it exists: P

+4
source

Source: https://habr.com/ru/post/1412426/


All Articles