As follows
Copy Code code as follows:
function person (name, age) {
THIS.name = name;
This.age = age;
}
var p = new person (' Lily ', 20);
It's strange to discover that some library code creates regular objects in a way that doesn't need to be new. As follows
Copy Code code as follows:
var reg = RegExp (' ^he$ ');
Test discovery uses or does not use new, and finally returns the regular objects, and typeof they are all "object".
Copy Code code as follows:
var reg1 = new RegExp (' ^he$ ');
var reg2 = RegExp (' ^he$ ');
Reg1.test (' he '); True
Reg2.test (' he '); True
Console.log (typeof REG1); Object
Console.log (typeof REG2); Object
Well, that's good, the code works fine.
If you don't write new at all, you'll save code. Is this the case with other types? Try String/number/boolean.
Copy Code code as follows:
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 the regular situation. Regular is object regardless of whether it is new,typeof or not.
But String/number/boolean type, new object typeof return is "Object", not new typeof return is "string".
Where new is not applicable, other types can be converted to strings, numbers, and Boolean types, respectively.
OK, then go back to the person class in the header. Can we write our own classes without generating objects with the new operator?
Copy Code code as follows:
function person (name, age) {
THIS.name = name;
This.age = age;
}
var p = person (' lily ', 20);
Console.log (P); Undefined
Return to undefined, obviously not. So it's whimsical to want to create a person instance without new.
What if it has to be implemented? In fact, it is OK, as follows
Copy Code code as follows:
function person (name, age) {
THIS.name = name;
This.age = age;
if (This===window) {
Return to new person (name, age);
}
}
var p = person (' lily ', 20); Object
Slightly modified the next person class. In fact, the internal distinction between the next person is as a constructor or function execution.