Skip to content Skip to sidebar Skip to footer

How Do I Redefine Myobject's Main Function, E. G. What Myobject() Does, Without Damaging Myobject's Properties, E. G. Myobject.foo?

I've got a legit JS question which is kinda hard to explain. Please forgive my unintelligible manner of speaking and try to grasp the idea. :P In JS objects can have properties. Yo

Solution 1:

What is the correct term for the function of such a function-object? I'll call it "function-object's main function" below.

It's called a "function". The properties of the (function) object that are functions themselves are called "methods". If you're talking about methods on a constructor function, you also call them "static methods" (of the "class").

How do i redefine the function-object's main function while leaving other function-object's properties intact?

You cannot. The call behaviour of a function is immutable in javascript.

All you can do is create a new function, overwrite the variable in which the old one was stored with it, and copy over all properties.

Solution 2:

Question 1: Adding user defined properties to functions is not recommended, because you don't control what properties functions have, so you can't know for sure if you are going to shadow another property. Since it is not recommended, I don't think there is a correct term for that. Personally, I would call them functions with user defined properties.

Question 2: The code myFunctionObject = function () { return "Another function here"; } sets myFunctionObject to a different object (function () { return "Another function here"; }). So, you need to pass the properties of your old object to the new one. One way of doing that is by using functions that add properties instead of adding properties with assignment.

functionaddBar(o){
    o.bar = "Bar";
    return o;
}

myFunctionObject = addBar(function () { return1; });
myFunctionObject = addBar(function () { return"Another function here"; });
console.log(myFunctionObject.bar);

Post a Comment for "How Do I Redefine Myobject's Main Function, E. G. What Myobject() Does, Without Damaging Myobject's Properties, E. G. Myobject.foo?"