字面量模式声明一个对象实例
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 Cricle(radius) {
this.radius = radius
this.draw = function (){
console.log("draw")
}
}
let cricle = new Cricle(2)
cricle.constructor
/*
ƒ Cricle(radius) {
this.radius = radius
this.draw = function (){
console.log("draw")
}
}
*/
Criicle.constructor
// ƒ Function() { [native code] }
说明两点:构造函数创建(new)的对象实例,其构造器为该构造函数。函数本身的构造器是 Function对象。
new 关键字,做了四件事。创建空对象实例、设置空对象的构造器为构造函数、将 this 指向该对象实例、返回 this(如果构造函数没有返回值)。
参考
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new