new 到底是个什么东西?

简单的来说 new 是生成一个实例的语法糖,帮助我们减少一些代码。

没有 new 时我们如何生成实例?

  1. 使用 this 关键字来实现。
function People(name) {
  this.name = name
  this.__proto__ = People.prototype
  return this
}

People.prototype = {
  sayName: function() { console.log(this.name) }
}

let ben = People.call({}, 'ben')
  1. 或不使用 this,代码能够更好的阅读。
function People(name) {
  let obj = {}
  obj.name = name
  obj.__proto__ = People.prototype
  return obj
}

People.prototype = {
  sayName: function() { console.log(this.name) }
}

let ben = People('ben')

使用 new 来生成实例

function People(name) {
  this.name = name
}
//推荐写法
People.prototype.sayName = function(){
  console.log(this.name)
}
/* 或者
People.prototype = {
  constructor: People,
  sayName: function() { console.log(this.name) }
}
*/

let ben = new People('ben')

由上述例子 new 将帮助我们完成以下一些操作:

  1. 创建临时对象,使用 this 就可以访问。
  2. 绑定原型,new 指定原型了为 prototype。
  3. return 临时对象。

完。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容