Objects Created in JS can be directly created using the direct quantity method. Here we discuss the definition of a constructor (function. As follows:
Function Person (name, age ){
This. name = name;
This. age = age;
}
Var p = new Person ('lily', 20 );
It is strange to find that the method of creating a regular object in some library code does not require new. As follows:
Var reg = RegExp ('^ he $ ');
The test shows that if you use or do not use new, the regular objects are returned at the end, and the typeof objects are all "objects ".
Var reg1 = new RegExp ('^ he $ ');
Var reg2 = RegExp ('^ he $ ');
Reg1.test ('hes'); // true
Reg2.test ('hes'); // true
Console. log (typeof reg1); // object
Console. log (typeof reg2); // object
Well, the code runs normally.
If this is the case, no new is written, which saves the amount of code. Is the same for other types? Try String/Number/Boolean.
Var str1 = new String (1 );
Var str2 = String (1 );
Var num1 = new Number ('1 ');
Var num2 = Number ('1 ');
Var boo1 = new Boolean (1 );
Var boo2 = Boolean (1 );
Console. log (typeof str1); // object
Console. log (typeof str2); // string
Console. log (typeof num1); // object
Console. log (typeof num2); // number
Console. log (typeof boo1); // object
Console. log (typeof boo2); // boolean
As you can see, it is different from regular expressions. Regular Expressions are all objects regardless of whether they are new or typeof.
But for the String/Number/Boolean type, the new object typeof returns "object", and the non-new typeof returns "string ".
That is, if new is not applicable, other types can be converted into strings, numbers, and Boolean types.
Now, return to the Person class in the beginning. That is, can we use the new operator to generate objects for classes we write ourselves?
Function Person (name, age ){
This. name = name;
This. age = age;
}
Var p = Person ('lily', 20 );
Console. log (p); // undefined
Undefined is returned, obviously not. Therefore, it is whimsical to create a Person instance without the need of a new one.
What if I have to implement it? In fact, this is also true, as shown below:
Function Person (name, age ){
This. name = name;
This. age = age;
If (this = window ){
Return new Person (name, age );
}
}
Var p = Person ('lily', 20); // object
Slightly changed the Person class. In fact, it distinguishes whether the Person is executed as the constructor or function.
From snandy