原文:javascript 如何实现一个 new - 每天一个JavaScript小知识@Js中文网 · 码农进阶题库

原文地址:https://www.javascriptc.com/interview-tips/zh_cn/javascript/javascript-implement-new/

题目描述:

如何实现一个 new

解题:

  • 思路一:
    // 实现一个new
    var Dog = function(name) {
    this.name = name
    }
    Dog.prototype.bark = function() {
    console.log('wangwang')
    }
    Dog.prototype.sayName = function() {
    console.log('my name is ' + this.name)
    }
    let sanmao = new Dog('三毛')
    sanmao.sayName()
    sanmao.bark()
    // new 的作用
    // 创建一个新对象obj
    // 把obj的__proto__指向Dog.prototype 实现继承
    // 执行构造函数,传递参数,改变this指向 Dog.call(obj, ...args)
    // 最后把obj赋值给sanmao
    var _new = function() {
    let constructor = Array.prototype.shift.call(arguments)
    let args = arguments
    const obj = new Object()
    obj.__proto__ = constructor.prototype
    constructor.call(obj, ...args)
    return obj
    }
    var simao = _new(Dog, 'simao')
    simao.bark()
    simao.sayName()
    console.log(simao instanceof Dog) // true
    
  • 思路二:
    function _new(fn, ...arg) {
      const obj = Object.create(fn.prototype);
      const ret = fn.apply(obj, arg);
      return ret instanceof Object ? ret : obj;
    }
    
  • 思路三:
  • 先理清楚 new 关键字调用函数都的具体过程,那么写出来就很清楚了

  • 1.首先创建一个空的对象,空对象的__proto__属性指向构造函数的原型对象
  • 2.把上面创建的空对象赋值构造函数内部的this,用构造函数内部的方法修改空对象
  • 3.如果构造函数返回一个非基本类型的值,则返回这个值,否则上面创建的对象
function _new(fn, ...arg) {
	var obj = Object.create(fn.prototype);
	const result = fn.apply(obj, ...arg);
	return Object.prototype.toString.call(result) == '[object Object]' ? result : obj;
}

扩展阅读: