new 运算符实现细节

2017-11-16  本文已影响0人  yyyzhen
function Person(name) {
    this.name = name;
}
Person.prototype.getName = function() {
    return this.name
}
var a = new Psrson('sven')
console.log(a.name)  // 'sven'
console.log(a.getName())  //  'sven'
console.log(Object.getPrototypeOf(a) === Person.prototype)  // true
console.log(a)

由上面这个例子可以知道new在执行时做了哪些事情:

  function Person(name) {
    this.name = name;
  }

  Person.prototype.getName = function() {
    return this.name;
  }

  var objectFactory = function() {
    var obj = new Object(),
      Constructor = [].shift.call(arguments);
    obj.__proto__ = Constructor.prototype;
    var ret = Constructor.apply(obj, arguments);
    return typeof ret === 'object' ? ret : obj;
  }
  var a = objectFactory(Person, 'sven')

  console.log(a.name)
  console.log(a.getName())
  console.log(Object.getPrototypeOf(a) === Person.prototype)
console.log(a)

可以看出,上下两个并没有什么区别

上一篇 下一篇

猜你喜欢

热点阅读