js 面向对象之构造器与工厂函数
一、字面量模式声明一个对象
let m = {name: "lisi", age:15} m.constructor // ƒ Object() { [native code] } Object.constructor // ƒ Function() { [native code] }
①每个对象都有构造函数。
②字面量形式的实例的构造函数通常是 Object。
③Object、Function与普通函数 的构造函数都是 Function。
二、构造函数模式
function Circle(radius) { this.radius = radius this.draw = function (){ console.log("draw") } } // new 操作符做了4件事 let c1 = new Circle(2) let Circle2 = new Function("radius", ` this.radius = radius this.draw = function (){ console.log("draw") } `)
说明:
When the code new Foo(...)
is executed, the following things happen:
- A new object is created, inheriting from
Foo.prototype
. - The constructor function
Foo
is called with the specified arguments, and withthis
bound to the newly created object.new Foo
is equivalent tonew Foo()
, i.e. if no argument list is specified,Foo
is called without arguments. - The object (not null, false, 3.1415 or other primitive types) returned by the constructor function becomes the result of the whole
new
expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
总结:
构造函数的目的是创建新实例。如果构造函数的返回值是一个对象,那么这个新实例就是该返回值。
如果构造函数的返回值不是一个对象,那么 new 操作符会创建一个 Object,绑定构造函数的this到这个 Object,最后返回 this。如果不使用 new 操作符,则不会创建这个 Object。
开闭原则
function Circle(radius) { this.radius = radius // 定义闭包共享变量 let defaultLocation = { x: 0, y: 0 } this.draw = function () { console.log("draw") } //提供可读权限(但不可写) Object.defineProperty(this, 'defaultLocation', { get: function () { this.defaultLocation } }) }
参考
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
https://blog.csdn.net/luanpeng825485697/article/details/78009093