newPromise / js-

0 stars 0 forks source link

检测原型继承的 instanceof 方法 #9

Open newPromise opened 6 years ago

newPromise commented 6 years ago

instanceof 用来判断一个对象的原型链上是否存在一个构造函数的 prototype 原型属性

用法:

Object instanceof constructor

Object 的原型链上是否存在 构造函数 constructor 的 prototype 原型属性

function bar ( ) {
}
let foo = new bar();
console.log(foo instanceof bar); // true
newPromise commented 6 years ago

使用 instanceof 可以用来检测一个变量的类型,比如检测数组

let arr =   [1,2,4,5];
console.log(arr  instanceof  Array);
// true

因为使用 instanceof 进行检测的是判断 arr 的 原型链上是否存在 Array 的原型属性 当然是存在的,因为上面的代码中,arr 相当于 Array 的一个实例, 对于 arr 上的数组方法实际上是继承自 Array.prototype 上的方法得来的。

现在我明白了, 为什么我们可以这样创建数组: let arr = new Array(2)

newPromise commented 6 years ago

2017-9-30 号补充: 使用 instanceof 方法检测到的对象原型只能检测到最后一个原型 或者说, 使用这种方法检测到的是原型链的终点

function B () {
}
let a = new B();

function C() {
}

B.prototype = new C ();

a instanceof B 
// false

a instanceof C

// true, 这里 因为 C 继承了 B 所以使用 这种方法返回的是 true
newPromise commented 6 years ago

调用 new 的过程中发生的事情

let obj = new Base();

let obj = {};  // 创建一个新的空对象
obj._proto_ = Base.prototype; // 执行原型链接, 将这个对象的原型指向构造函数的原型
Base.call(obj); // 使用 call 将 `Base` 内部的 `this` 值指向了 `obj` 对象

将一个函数进行原型链接的方法还有另外一种方法: 使用 Object.create 的方法也可以实现原型链接。

let Objcon = function () {};
let obj = Object.create(Objcon);
obj instanceof Objcon
// 进行判断得到在 obj 上面存在 Objcon 的原型属性。