昨天我接受了一次采访,有一个编写JavaScript类的任务,该类可以用多个新对象创建,并且必须是其所有父对象的实例。我尝试使用Function.bind()来做到这一点,但是没有用。
function JSObject() {
return JSObject.bind(null);
}
var obj1 = new JSObject();
var obj2 = new obj1();
var obj3 = new obj2();
console.log(obj2 instanceof obj1); // prints false, expected true
console.log(obj3 instanceof obj2); // prints false, expected true
console.log(obj3 instanceof obj1); // prints false, expected true
console.log(obj1 instanceof obj2); // prints false, expected false
console.log(obj1 instanceof obj3); // prints false, expected false
let objects = [JSObject, new JSObject()];
for (let i = 0; i < 10; i++) {
objects.push(new objects[objects.length - 1]());
}
for (let obj of objects) {
const objProt = Object.getPrototypeOf(obj);
const objProtProt = Object.getPrototypeOf(obj.prototype);
const funcProt = Object.getPrototypeOf(Function);
const funcProtProt = Object.getPrototypeOf(Function.prototype);
console.log(objProt === funcProt); // expected true
console.log(objProtProt === funcProtProt); // expected true
}
此外,我无法直接更改原型,测试已检查对象的原型必须为Function
答案 0 :(得分:1)
这实际上不是“类”,因为您无法区分构造函数和实例。每个“构造函数”函数都只会创建本身就是“子类”的新对象。
function inherit(parent) {
function object() {
return Object.setPrototypeOf(inherit(object), object.prototype);
}
object.prototype = Object.create(parent.prototype);
return object;
}
var JSObject = inherit(Function);
或使用ES6:
function inherit(parent) {
return class object extends parent {
constructor() {
return Object.setPrototypeOf(inherit(object), new.target.prototype);
}
}
}
const JsObject = inherit(Function);
这些甚至达到obj instanceof Function
和obj.prototype instanceof Function
(当然还有instanceof Object
)。您无法达到Object.getPrototypeOf(obj) == Function.prototype
和Object.getPrototypeOf(obj.prototype) == Object.prototype
的其他要求。 (假设我们不使用欺骗您测试的有状态代理)。