Rumah > hujung hadapan web > tutorial js > OOP - Cabaran JavaScript

OOP - Cabaran JavaScript

Patricia Arquette
Lepaskan: 2024-11-04 02:27:01
asal
655 orang telah melayarinya

OOP - JavaScript Challenges

Anda boleh menemui semua kod dalam siaran ini di repo Github.


Cabaran berkaitan OOP


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
Salin selepas log masuk

baru

/**
 * @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' }
Salin selepas log masuk

Rujukan

  • 60. buat operator baharu anda sendiri - BFE.dev
  • 90. tulis contoh anda sendiri - BFE.dev
  • contoh - MDN
  • baharu - MDN
  • Perantaian kaedah - Wikipedia.org
  • 2726. Kalkulator dengan Kaedah Rantaian - LeetCode

Atas ialah kandungan terperinci OOP - Cabaran JavaScript. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan