字面量模式声明一个对象实例
let m = {name: "lisi", age:15}
m.constructor
// ƒ Object() { [native code] }
Object.constructor
// ƒ Function() { [native code] }
解释上面的输出:
Object、Function 是 js 内置的包装类(引用类)对象。
每个对象实例都有构造器, 构造器是函数, 亦称之为构造器函数。字面量形式的对象构造器通常是 Object,Object、Function与普通函数 的构造器都是 Function。
new 构造函数模式创建对象实例
function Circle(radius) {
this.radius = radius
this.draw = function (){
console.log("draw")
}
}
// new 操作符做了4件事
let c1 = new Circle(2)
// 第二件事证明:实例的构造器属性为当前函数
console.log(c1.constructor)
/* output:
ƒ Circle(radius) {
this.radius = radius
this.draw = function (){
console.log("draw")
}
}
*/
// 构造器本身也是一个 Function 函数
console.log(Circle.constructor)
/* output:
ƒ Function() { [native code] }
*/
let Circle2 = new Function("radius", `
this.radius = radius
this.draw = function (){
console.log("draw")
}
`)
说明两点:
构造函数创建(new)的对象实例,其构造器为该构造函数。函数本身的构造器是 Function对象。
new 关键字,做了四件事。创建空对象实例、设置空对象实例的构造器为当前构造对象、将 this 指向该对象实例、返回 this(如果构造函数没有返回值)。
参考
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
原文:https://www.cnblogs.com/lemos/p/11645156.html