一、字面量模式声明一个对象

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:

  1. A new object is created, inheriting from Foo.prototype.
  2. The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
  3. 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

最新文章

  1. KnockoutJS 3.X API 第七章 其他技术(4) 速率限制
  2. JS学习笔记8之 BOM-浏览器对象模型
  3. nodejs——qureystring的作用
  4. css 布局absolute与relative的区别
  5. H2嵌入式数据库
  6. CCS学习资料汇总
  7. Mysql show Status参数详解
  8. Kurskal算法(克鲁斯卡尔算法)
  9. Android的FrameLayout使用要注意的问题
  10. ListView控件的Insert、Edit和Delete功能(第二部分)
  11. CSS当中数学表达式calc
  12. 加域电脑登陆系统后桌面文件丢失,登录系统提示用户名为“Temp”。
  13. Bootstrap&bxslider
  14. 超酷的Prezi在线ppt制作网站
  15. 常见web漏洞
  16. Appium安装教程
  17. numpy切片和布尔型索引
  18. JavaWeb——监听器
  19. 日志统计--蓝桥杯--vector
  20. react中图片校验码实现以及new Buffer()使用方法

热门文章

  1. windows环境下安装: VMware 15 + centos 7
  2. Eclipse下Maven安装和配置
  3. mysql 报错ERROR 2002 (HY000): Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)
  4. [转帖]深度分析HBase架构
  5. google test 打印派生类对象
  6. 在做爬虫或者自动化测试时新打开一个新标签页,必须使用windows切换
  7. python 之 前端开发( JavaScript变量、数据类型、内置对象、运算符、流程控制、函数)
  8. PB之常用函数
  9. NIO堆外内存与零拷贝
  10. 跟我一起学docker