OOP - JavaScript 挑战
您可以在 github 仓库中找到这篇文章中的所有代码。
oop 相关挑战
实例化
/** * @param {any} obj * @param {target} target * @return {boolean} */ // one-line solution function myinstanceof(obj, fn) { return fn.prototype.isprototypeof(obj); } function myinstanceof(obj, fn) { if (typeof obj !== "object" || obj === null) { return false; } if (typeof fn !== "function") { return false; } let proto = object.getprototypeof(obj); while (proto) { if (proto === fn.prototype) { return true; } proto = object.getprototypeof(proto); } return false; } // usage example class a {} class b extends a {} const b = new b(); console.log(myinstanceof(b, b)); // => true console.log(myinstanceof(b, a)); // => true console.log(myinstanceof(b, object)); // => true function c() {} console.log(myinstanceof(b, c)); // => false c.prototype = b.prototype; console.log(myinstanceof(b, c)); // => true c.prototype = {}; console.log(myinstanceof(b, c)); // => false
新的
/** * @param {Function} constructor * @param {any[]} args * `myNew(constructor, ...args)` should return the same as `new constructor(...args)` */ function myNew(constructor, ...args) { const obj = {}; Object.setPrototypeOf(obj, constructor.prototype); const result = constructor.call(obj, ...args); if (typeof result !== "object" || result == null) { return obj; } else { return result; } } // Usage example function Person(name) { this.name = name; } const person = myNew(Person, "Mike"); console.log(person); // => Person { name: 'Mike' }
参考
- 60。创建您自己的新运算符 - bfe.dev
- 90。编写你自己的实例 - bfe.dev
- 实例 - mdn
- 新 - mdn
- 方法链 - wikipedia.org
- 2726。带方法链的计算器 - leetcode
以上就是OOP - JavaScript 挑战的详细内容,更多请关注其它相关文章!