6

How to delete a function from constructor?

If there is a function called greet in the Person constructor, how do I 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;
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
XP1
  • 6,910
  • 8
  • 54
  • 61
  • 1
    possible duplicate of [How to remove a property from a javascript object](http://stackoverflow.com/questions/208105/how-to-remove-a-property-from-a-javascript-object) – Felix Kling May 14 '12 at 20:45

2 Answers2

6
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 your very rarely see but I assure you, it exists :P

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 2
    Surely you mean `delete personInstance.greet`, not `delete Person.greet` (the function does not have a property `greet`). – Felix Kling May 14 '12 at 20:43
  • What if I want to delete from the constructor when there are no instances? – XP1 May 14 '12 at 20:44
  • 1
    @XP1: If there are no instances, then `this.greet` does not exist, since the constructor was never executed. So in this regard your question does not make much sense. Maybe you want to edit the source code or override `Person` with your own function which does not contain this part. – Felix Kling May 14 '12 at 20:45
  • So every time I instantiate a `Person`, I have to delete the `greet` function? This is what I am trying to avoid. – XP1 May 14 '12 at 20:48
  • 2
    @XP1: Then override `Person` with your own function. Or create a wrapper: `function PersonWrapper(name) { var p = new Person(name); delete p.greet; return p;}`... fact is that you cannot change the source of a function. – Felix Kling May 14 '12 at 20:49
  • Thanks, @Felix Kling! I'll use the wrapper. – XP1 May 14 '12 at 20:51
3

You cannot change the source of a function. If you want to change that function's behaviour, you have to options:

Override the function with your own. This is easy if the function is standalone. Then you can really just define

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

after the original function was defined. But if prototypes and inheritance are involved, it can get tricky to get a reference to the original prototype (because of the way how function declarations are evaluated).

Ceate a wrapper function which creates and instance and removes the properties you don't want:

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

This approach is also limited since you can only change what is accessible from the outside. In the example you provided it would be sufficient though.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143