javascript - 如何在不调用构造函数和 new 关键字的情况下创建对象
问题描述
我有一个函数 Person(我在这个例子中使用 ES5)
function Person(name) {
this.name = name
}
Person.prototype.printName = function() {
console.log(this.name)
}
据我了解,我新创建的对象“ .proto”引用应该等于 Person.prototype (就像 new 运算符一样)。我使用 Object.create 设置适当的proto。我应该如何将其他参数传递给我新创建的实例,以便我的“TestName”参数应该等于 this.name
创建实例函数本身:
function createInstance(constructor, ...args) {
let instance = Object.create(constructor.prototype)
instance.call(constructor, args)
return instance
}
let instance = createInstance(Person, 'TestName')
console.log(instance)
解决方案
推荐阅读
- ffmpeg - FFMPEG 将 H265 视频从 10 位转码为 8 位
- javascript - React Material-UI最简单的Hello Wold测试中的无效钩子调用错误
- encryption - 这种双挂锁类比与公私钥加密+签名之间是否有任何功能差异?
- java - JLabel上的透明背景GIF表现奇怪
- python - Performing for loop in pandas
- c# - System.ArgumentNullException:值不能为空 ASP.NET MVC5
- r - R。如何对名称中带有 () 括号的行进行子集化?
- visual-c++ - 与结构成员变量关联的对话框控件
- javascript - Highcharts - PieChart 在调用 this.setState 的点击事件上刷新
- c++ - 试图转换 wxVector 的一个组件
这是 wxString 到 wxStringArray 但程序不想