Home  >  Article  >  Web Front-end  >  OOP - JavaScript Challenges

OOP - JavaScript Challenges

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 02:27:01560browse

OOP - JavaScript Challenges

You can find all the code in this post at the repo Github.


OOP related challenges


instanceof

/**
 * @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

new

/**
 * @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' }

Reference

  • 60. create your own new operator - BFE.dev
  • 90. write your own instanceof - BFE.dev
  • instanceof - MDN
  • new - MDN
  • Method chaining - Wikipedia.org
  • 2726. Calculator with Method Chaining - LeetCode

The above is the detailed content of OOP - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn