【javascript 基礎篇】prototype & constructor & instanceof

【javascript 基礎篇】prototype & constructor & instanceof

以前每件事都差很少,直到如今才發現差不少。

如今才發現理清一件事的原委是多麼快樂的一件事,咱們共同勉勵。javascript

懶得扯淡,直接正題java

不基於例子的講原理都是扯淡,知乎同樣的舉例都是賣弄函數

例子

function A () {

};

A.prototype = {

};

function B () {

};

var a = new A();
B.prototype  = new A();
var b = new B();

console.log(a.constructor); //Object
console.log(A.constructor); //Function
console.log(a.hasOwnProperty('constructor')); // false
console.log(A.hasOwnProperty('constructor')); // false
console.log(a instanceof A); // true

console.log(b.constructor); // Object
console.log(B.constructor); // Function
console.log(b.hasOwnProperty('constructor')); // false
console.log(B.hasOwnProperty('constructor')); // false
console.log(b instanceof B); // true
console.log(b instanceof A); // true

prototype

constructor

例子分析

console.log(a.constructor); //Object
console.log(A.constructor); //Function
console.log(b.constructor); // Object
console.log(B.constructor); // Function

首先須要明確 constructor 屬性是 Object.prototype 對象上的, Object.prototype.hasOwnProperty('constructor') === true,而實例對象上的 constructor 屬性是從其原型鏈中取。spa

  1. a的原型對象是A.prototype,指向了一個空對象,因此從Object.prototype 裏面 查找 constructor 屬性,返回 Object
  2. 任何一個函數都是都是 Function 的一個實例,Function.prototype.constructor === Function
  3. 再看一下 b,是 B 的實例,B 的 prototype 指向了 A 的實例,因此 b.constructor = a.constructor === Object
  4. B.constructor 同 第二種狀況同樣

instanceof

語法

object instanceof constructor
# 參數
- object 檢測的對象
- constructor 構造函數

用途

檢測 constructor.prototype 是否存在於object的原型鏈上prototype

例子分析

# 此處爲文章前面的例子,只是把對於 instanceof 的判斷集中起來
console.log(a instanceof A); // true
console.log(b instanceof B); // true
console.log(b instanceof A); // true

clipboard.png


MDN instanceof有下面的例子(精簡化)code

function C(){} 
var o = new C();
o instanceof C; // true,由於 Object.getPrototypeOf(o) === C.prototype
o instanceof Object; // true,由於Object.prototype.isPrototypeOf(o)返回true
C.prototype instanceof Object // true,同上

C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false,C.prototype指向了一個空對象,這個空對象不在o的原型鏈上.

乍一看,上面的例子,始終對於最後 o instanceof C 返回 false 不理解,其實只要明白 object.__proto__ 和 Constructor.prototype 是兩個引用值,在使用 Constructor 建立實例 object 時, object.__proto__ === Constructor.prototype,以後 object.__proto__ 改變和 Constructor.prototype 任意其一改變都會致使最後 object.__proto__ !== Constructor.prototype對象

hasOwnProperty

例子分析

console.log(a.hasOwnProperty('constructor')); // false
console.log(A.hasOwnProperty('constructor')); // false
console.log(b.hasOwnProperty('constructor')); // false
console.log(B.hasOwnProperty('constructor')); // false

constructor 屬性是從原型對象上繼承的blog

相關資料

MDN instanceof
MDN constructor
MDN hasOwnProperty
MDN Prototype繼承

相關文章
相關標籤/搜索