As follows
function Person(name, age) {
this.name = name;
this.age = age;
}
var p = new Person('lily', 20);
Discover something It's strange how the library code creates regular objects without using new. As follows
var reg = RegExp('^he$');
The test found that whether new is used or not, the final returned objects are regular objects, and typeof them are all "object".
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, pretty good, the code runs normally.
If this is the case, just don’t write new at all, which will save the amount of code. Is this true for other types as well? 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 the regular case. Regularly, regardless of whether it is new or not, typeof is followed by object.
But for String/Number/Boolean types, 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 string, number and Boolean types respectively.
Okay, let’s go back to the Person class at the beginning of the chapter. That is, can the classes we write ourselves generate objects without using the new operator?
function Person(name, age) {
this.name = name;
this.age = age;
}
var p = Person('lily', 20);
console.log(p); // undefined
returns undefined, which is obviously not possible. Therefore, it is fanciful to create a Person instance without using new.
What if it has to be realized? In fact, it works, as follows
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 modified the Person class. In fact, it is distinguished internally whether Person is executed as a constructor or a function.