Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a function from constructor?

Tags:

javascript

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;
}
like image 429
XP1 Avatar asked May 14 '12 20:05

XP1


People also ask

Can you put functions in constructors?

Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval() . However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

Is there a delete function in JavaScript?

The delete operator removes a given property from an object. On successful deletion, it will return true , else false will be returned.

How do you stop a constructor?

The only way to "stop" a constructor is to throw an exception.

What does delete means in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


2 Answers

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

like image 64
Halcyon Avatar answered Oct 02 '22 14:10

Halcyon


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.

like image 21
Felix Kling Avatar answered Oct 02 '22 16:10

Felix Kling