admin管理员组

文章数量:1327849

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

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;
}
Share edited May 14, 2012 at 20:44 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked May 14, 2012 at 20:38 XP1XP1 7,1938 gold badges59 silver badges63 bronze badges 1
  • 1 possible duplicate of How to remove a property from a javascript object – Felix Kling Commented May 14, 2012 at 20:45
Add a ment  | 

2 Answers 2

Reset to default 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

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.

本文标签: javascriptHow to delete a function from constructorStack Overflow