OOP – JavaScript 挑战

oop - javascript 挑战

您可以在 github 仓库中找到这篇文章中的所有代码。

oop 相关挑战

实例化

/** * @param {any} obj * @param {target} target * @return {boolean} */// one-line solutionfunction 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 exampleclass a {}class b extends a {}const b = new b();console.log(myinstanceof(b, b)); // => trueconsole.log(myinstanceof(b, a)); // => trueconsole.log(myinstanceof(b, object)); // => truefunction c() {}console.log(myinstanceof(b, c)); // => falsec.prototype = b.prototype;console.log(myinstanceof(b, c)); // => truec.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 examplefunction Person(name) {  this.name = name;}const person = myNew(Person, "Mike");console.log(person); // => Person { name: 'Mike' }

登录后复制

参考

60。创建您自己的新运算符 – bfe.dev90。编写你自己的实例 – bfe.dev实例 – mdn新 – mdn方法链 – wikipedia.org2726。带方法链的计算器 – leetcode

以上就是OOP – JavaScript 挑战的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2658684.html

(0)
上一篇 2025年3月7日 10:24:49
下一篇 2025年3月7日 10:24:56

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论