ES6 中 Proxy 的 getPrototypeOf 陷阱是怎么回事?
发布于 5 年前 作者 ta7sudan 2640 次浏览 来自 问答

如下代码

function Test() {
}

const a = new Proxy({}, {
	getPrototypeOf() {
		return Array.prototype;
	}
});

console.log(a instanceof Array); // true

const b = new Proxy({}, {
	getPrototypeOf() {
		return Test.prototype;
	}
});

console.log(b instanceof Test); // false
console.log(b instanceof Test); // true
console.log(b instanceof Test); // true

为什么 a, b 两个的结果完全不一样, 原生类和我自己定义的类难道有什么区别?

而对于后面两个结果, 难道 getPrototypeOf 存在副作用?

另一个例子如下

class Test {}

const a = new Proxy({}, {
	getPrototypeOf() {
		return Array.prototype;
	}
});

console.log(a instanceof Array); // true

const b = new Proxy({}, {
	getPrototypeOf() {
		return Test.prototype;
	}
});

console.log(b instanceof Test); // true
console.log(b instanceof Test); // true
console.log(b instanceof Test); // true

如果把函数换成 class, 则出现了预期之中的结果, 但是 js 中 class 不是仅仅是语法糖吗? 为什么会有这样的区别?

补充环境

Node v10.15.1 64bit 和 Chrome 73.0.3683.86 复现

FF 66.0.1 64bit 则全都是 true, 符合预期

再补充下, 使用 Object.getPrototypeOf() 则结果都符合预期, 出问题的只有 instanceof

function Test() {
}

const a = new Proxy({}, {
	getPrototypeOf() {
		return Array.prototype;
	}
});

console.log(Object.getPrototypeOf(a) === Array.prototype); // true

const b = new Proxy({}, {
	getPrototypeOf() {
		return Test.prototype;
	}
});
console.log(Object.getPrototypeOf(b) === Test.prototype); // true
console.log(Object.getPrototypeOf(b) === Test.prototype); // true
console.log(Object.getPrototypeOf(b) === Test.prototype); // true
2 回复

console.log(b instanceof Test); // false console.log(b instanceof Test); // true console.log(b instanceof Test); // true 第一行没问题?

回到顶部