js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

实现new

Open Sunny-117 opened this issue 3 years ago • 3 comments

(1)首先创建了一个新的空对象 (2)设置原型,将对象的原型设置为函数的 prototype 对象。 (3)让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性) (4)判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。

function myNew(constructorFn, ...args) {
    let newObj = {}
    newObj.__proto__ = constructorFn.prototype;
    // newObj = Object.create(constructor.prototype);
    let result = constructorFn.apply(newObj, args)
    return result instanceof Object ? result : newObj
}
function Animal(name) {
    this.name = name;
}
let animal = myNew(Animal, 'dog')
console.log(animal);

Sunny-117 avatar Nov 03 '22 07:11 Sunny-117

function myNew(constructor, ...args) {
  const obj = Object.create(constructor.prototype);
  const result = constructor.apply(obj, args);
  return result instanceof Object ? result : obj;
}

kangkang123269 avatar Feb 20 '23 10:02 kangkang123269

function myNew(){
    let obj = {};
    let con = [].shift.call(arguments);
    obj.__proto__ = con.prototype;
    let res = con.call(obj, ...arguments);
    return res instanceof Obejct ? res : obj;
}

bearki99 avatar Mar 05 '23 03:03 bearki99

function myNew(constructorFn, ...args) {
  // 1. 创建一个空对象,该对象的原型指向构造函数的 prototype 属性
  const obj = Object.create(constructorFn.prototype);

  // 2. 将这个空对象作为 this 上下文绑定到构造函数上,并传入参数
  const result = constructorFn.apply(obj, args);

  // 3. 如果构造函数返回了一个对象,则返回这个对象;否则返回上面创建的对象
  return typeof result === "object" && result !== null ? result : obj;
}
function Animal(name) {
  this.name = name;
}
let animal = myNew(Animal, "dog");
console.log(animal);

dizao006 avatar Oct 14 '24 08:10 dizao006