Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Cases for Attaching Function and Property to Object

Tags:

javascript

What sort of use cases would there be for attaching both a function AND property to your object? I haven't seen this done in Production. Is this considered bad practice?

For example:

var actor = function() {
    console.log('I\'ll be back!');
}

actor.name = 'Arnold Schwarzenegger';
like image 674
Jon Avatar asked Mar 31 '26 07:03

Jon


1 Answers

Function inherits from Object. Function.name is a special property that refers to the name of the function. For anonymous functions you can change the name property to whatever you want.

Is changing .name a good practice?

I would say, no. Changing the .name property doesn't achieve anything other than making things more confusing.

Your Question

attaching both a function AND property to your object

This is not what your code is doing. actor is a function, which is also an object. You can always add properties to any object except null. In fact, Function.prototype already comes with a lot of methods (properties) as defined in ES6.

Adding Properties to a Function Instance

In general, adding properties to a function instance is not a bad practice. This practice is used everywhere from creating static methods and even in jQuery (e.g. $.get):

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

Person.clone = function(p){
    return new Person(p.name);
};

var p1 = new Person("Alex"),
    p2 = Person.clone(p1);       // clone p1

It is a feature of the language and you should definitely use it if it fits your purpose.

like image 81
Derek 朕會功夫 Avatar answered Apr 02 '26 20:04

Derek 朕會功夫



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!