当前位置:网站首页>js 构造函数 return 非空对象,其实例化的对象在原型上的差异
js 构造函数 return 非空对象,其实例化的对象在原型上的差异
2022-07-30 12:07:00 【ymzhaoUSTB】
一、构造函数
先看下构造函数的定义
ECMAScript 中的构造函数是用于创建特定类型对象的。构造函数也是函数,只是使用 new
操作符调用构造函数会执行如下操作:
(1) 在内存中创建一个新对象
(2) 这个新对象内部的 [[Prototype]]
特性被赋值为构造函数的 prototype
属性
(3) 构造函数内部的 this
被赋值为这个新对象(即 this 指向新对象)
(4) 执行构造函数内部的代码(给新对象添加属性)
(5) 如果构造函数返回非空对象,则返回该对象;否则,返回刚创建的新对象
二、分析
如果不清楚构造函数的定义,就没有必要看这部分了
根据定义,这里将构造函数分为两种:有无返回非空对象。具体区别在哪儿,之前从未细想过
示例1:实例在原型上的不同
function Foo(name) {
this.name = name
}
function Bar(name) {
this.age = 27
return {
name }
}
let foo = new Foo('Tom'), bar = new Bar('Tom')
console.log(foo.__proto__ === Foo.prototype) // true
console.log(bar.__proto__ === Bar.prototype) // false
上图中也可以看出,foo的原型指向Foo的原型,而bar的原型指向Object的原型
示例2
通过这个例子更明显的对比构造函数中的 this
与 return
的实例
function Foo(name) {
const _this = this
this.name = name
function test(){
console.log(this, _this)
}
return {
name: 'Tom',
test
}
}
let foo = new Foo('Anne')
console.log(foo)
foo.test()
执行 foo.test()
this
打印的是foo,即,实例化时return出来的对象_this
打印的是实例化过程中创建的新对象,根据定义,该对象原型指向构造函数的原型。相比之下,前者是对象字面量,其原型指向Object的原型
原型上的区别,意味着,上例中,foo的原型也不指向 Foo的原型,原型的构造函数也并非 Foo。
因此,foo无法访问Foo的原型属性与方法:
function Foo(name) {
const _this = this
this.name = name
function test(){
return _this
}
return {
name: 'Tom',
test
}
}
let foo = new Foo('Anne'), _this = foo.test()
Foo.prototype.age = 18
Foo.prototype.func = function() {
console.log(this.name, this.age)
}
console.log(!!foo.func, !!_this.func) // false true
_this.func() // Anne 18
针对这点,可以在构造函数内手动将返回的对象原型指向构造函数的原型
如果用不上原型链的话,可以直接忽视这点
function Foo(name) {
let res = {
}
res.__proto__ = Foo.prototype
return Object.assign(res, {
name })
}
let foo = new Foo('Anne')
Foo.prototype.age = 20
console.log(foo.age) // 20
边栏推荐
猜你喜欢
Interviewer: Redis bloom filter and the cuckoo in the filter, how much do you know?
打破原则引入SQL,MongoDB到底想要干啥???
Reverse linked list - recursive inversion method
历时两月,终拿字节跳动offer,算法面试题分享「带答案」
概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!
【32. 图中的层次(图的广度优先遍历)】
Vivado安装后添加器件库
Concepts of cloud-native applications and 15 characteristics of cloud-native applications
win下怎么搭建php环境的方法教程
维护数千规模MySQL实例,数据库灾备体系构建指南
随机推荐
CMake library search function does not search LD_LIBRARY_PATH
Mysql索引结构
SQL 根据时间范围查询数据
LeetCode_235_Last Common Ancestor of Binary Search Tree
unity对象池(学习)
关于File文件的相关知识
JD.com was brutally killed by middleware on two sides. After 30 days of learning this middleware booklet, it advanced to Ali.
什么是驱动程序签名,驱动程序如何获取数字签名?
IO/multiplexing (select/poll/epoll)
概率论的学习整理4:全概率公式
[BJDCTF2020]Cookie is so stable-1|SSTI注入
刷屏了!!!
int a=8,a=a++,a? int b=8,b=b+1,b?
13-GuliMall Basics Summary
What happened when the computer crashed?
nodeJs--fs模块
从“校园贷”到“直播带货”,追风少年罗敏一直行走在风口浪尖
Another blast!Ali's popular MySQL advanced collection is open source, reaching P7
【MySQL系列】-B+树索引和HASH索引有什么区别
Beijing, Shanghai and Guangzhou offline events丨The most unmissable technology gatherings at the end of the year are all gathered