Js adds attributes to the constructor

    var Foo = function(){
        this.age = 18;
        this.**getName** = function () {
            console.log("2");
        }
    }
    Foo.**getName** = function () {
        console.log("2");
    }
    

excuse me, is there any difference between these two getName properties?

Jun.09,2021
The properties in the

constructor are added to the instance; Foo.getName is the property of the Foo object.
for example: var foo = new Foo () , then getName of this instance foo is the instance property added in the constructor, while Foo.getName is the property of Foo object


one belongs to Foo object and the other belongs to object instance;


the first one is added to the instance and belongs to the instance property.
the second is to use the constructor as a function, and getName is added directly to the constructor.

you can test

var t = new Foo()
t.getName()   
t.constructor.getName()

observe the results of both, and I'm sure you can understand


one is the property of the prototype and the other is the property of the instance object

Menu