JavaScript学习日记 : Day15 - 原型与继承(二)

F.prototype

我们可以使用new F()这样的构造函数创建一个新object,如果F.prototype是一个object,那new操作符会使用这个object设定为新object的[[prototype]]。

这边的prototype只是F这个构造函数的一个属性。

let animal = {
  eats: true
};

function Cat(name) {
  this.name = name;
}

Cat.prototype = animal;

let cat = new Cat("White cat"); //  cat.__proto__ == animal

console.log( cat.eats ); // true

设置Cat.prototype = animal的字面意思是,当创建了new Cat时,会把创建的object的[[prototype]]指向animal。

F.prototype只有在new F时才会用到,如果在创建後,F.prototype有了变化(F.prototype = {anothoer object}),已经存在的obejct会保持旧有的继承,但是之後创建的objetc会继承新的。

默认的F.prototype, 构造器属性

每个函数都有prototype属性,即使提供它。默认的prototype是一个只有constructor属性的object,属性constructor指向函数自身。

function Cat() {}

/* default prototype
Cat.prototype = { constructor: Cat };
*/

可以检查一下 :

function Cat() {}
// by default:
// Cat.prototype = { constructor: Cat }

console.log( Cat.prototype.constructor == Cat ); // true

所以如果我们什麽都不做,constructor属性可以透过[[prototype]]继承给所有cat使用:

function Cat() {}
// by default:
// Cat.prototype = { constructor: Cat }

let cat = new Cat(); // inherits from {constructor: Cat}

console.log(cat.constructor === Cat); // true (from prototype)

我们可以使用constructor属性来创建一个新object。

function Cat(name) {
  this.name = name;
  alert(name);
}

let cat = new Cat("White cat");

let cat2 = new cat.constructor("Black cat");

当我们有一个object,但是不知道它使用了哪个构造器(例如它来自第三方library),并且我们需要一个类似的object,这时候这种方法就很方便。

但是这里需要注意的是,JavaScript并不能确保正确的constructor函数值。constructor只是默认存在函数的prototype,一但我们主动把它替换掉,constructor就不存在了。 例如:

function Cat() {}
Cat.prototype = {
  jumps: true
};

let cat = new Cat();
console.log(cat.constructor === Cat); // false

因此为了确保正确的constructor,我们可以选择添加/删除属性到默认的prototype,而不是将整个覆盖:

function Cat() {}

Cat.prototype.jumps = true

或是手动重新创建constructor属性:

Cat.prototype = {
  jumps: true,
  constructor: Cat
};

如此一来就能确保正确的constructor。


<<:  予焦啦!RISC-V 的计时器中断机制

>>:  Day13:今天来聊一下Microsoft Defender for Endpoint的配置警报和检测

Day26 Let's ODOO: ODOO Studio

今天来介绍Odoo studio,对於程序苦手或非程序人员,运用Odoo studio可以直接透过见...

Qualcomm announces next-gen X65 5G modem

Qualcomm has recently announced its upcoming 5G mo...

初探网路安全(二):密码怎麽被「试」出来的

每一年都可以看到新闻在报资安公司所统计出来的年度最烂密码,诸如以下 123456789 pictur...

Day 17 - Sorting Band Names without articles

前言 JS 30 是由加拿大的全端工程师 Wes Bos 免费提供的 JavaScript 简单应用...

Vaadin Pro Components 图表初探 - day26

目标 使用 Pro Components 制作图表 萤幕截图 汇出png图 Vaadin Chart...