JS function variable problem

A novice asks a perplexing question: why do you set the property age, to the function undefined

when taking properties from its instance object?
function test(){
    this.name = "fuck";
}
test.age = 10;

alert(test.age);//10
alert(new test().age); //undefined
Mar.04,2021
The

instance object can take the properties on the prototype chain of the constructor, but not the properties of the constructor itself.


test.age = 10; is assigned to the function object, and the function new is followed by a new object, but the constructor on the prototype points to it
test.age = 10; to test.prototype.age = 10;


 

use the factory method to generate the object (that is, using the test after the new keyword), new, we call it the "constructor", which can be approximately regarded as the "class" in other languages. the property loaded directly in the constructor can be regarded as the static property of the "class". The static property can only be accessed directly by the "class" and cannot be inherited by its instance.

as said upstairs, new test (). Age will have a value only if it is mounted on the test.prototype.age. If you can't understand it, you can directly think that the attribute under test.prototype is the public attribute under test "class", and the attribute under test is the static attribute of test "class"

.

all the above are unprofessional answers. I hope it will be helpful for you to understand

Menu