You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionBook(name){if(!(thisinstanceofBook)){// the constructor was called without "new".returnnewBook(name);}}varmyBook=Book(name);varmyBook1=Book(name);myBook.constructor===myBook1.constructor// true
构造函数已经是老生常谈的事情了。这里讲一些比较基础的东西。
先看下一个例子
首先判断this是否为Book的实例,不是就返回新的实例。经常用于解决在构造函数前面忘记使用
new
的情况,如果没有使用在function前面使用new,那就按正常的函数执行。那为什么这里可以这么使用?我们先看下
new
的原理到了第二步骤我们就可以看到myBook可以访问构造函数的prototype的constructor。
当执行第二步骤以后例子中的
if (!(this instanceof Book))
就不会被执行。所以this instanceof Book
可以判断当前函数是否使用new。第四步就是判断Book返回值的类型:
例子:
return 2属于值类型,包括String、布尔值、null、undefined等..如果是值类型,就丢弃返回instance。
如果是引用类型,就返回这个引用类型的对象
如果return的值是一个Number 对象,那么实例对象的值就是Number 对象。
原型链继承需要注意的一点
例子:
比较奇怪的是 Bmw.prototype.constructor = Bmw; 解释下为什么要这么处理。
假设如果没有这行
Bmw.prototype 实际上是 new Car() 的实例,结果导致Bmw prototype中的 constructor从丢失(ps: function创建后prototype已经有constructor值),
bmw1
对象在原型链中查询constructor的时候指向了构造函数Car
,这明显是错误的。因此这里修正了Bmw.prototype.constructor = Bmw
。同时还可以通过proto获取Car的构造函数。The text was updated successfully, but these errors were encountered: