js 面向对象之构造器与工厂函数

孤街醉人 提交于 2019-11-30 23:55:28

字面量模式声明一个对象实例

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!