OOP – JavaScript 挑战
收藏
一分耕耘,一分收获!既然都打开这篇《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 挑战》的详细内容,更多关于的资料请关注米云公众号!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除
- Win10键盘无法输入怎么办 Win10键盘无法输入解决方法
