如何重构JS类NewPlayer 支持通过new NewPlayer().init传参创建实例
JS类NewPlayer调用逻辑实现方案
你要的调用方式可以实现,核心是解决init方法赋值给外部变量后调用的this指向丢失的问题,有两种常见实现方案:
方案1:构造函数内绑定this
在构造函数中提前将init方法绑定到当前实例,方法定义保留在类原型上,适合需要复用方法的场景:
class NewPlayer { constructor() { this.player = {}; // 绑定init的this指向当前实例,赋值给外部变量后调用不会丢失上下文 this.init = this.init.bind(this); } init(domId, config, extraOptions) { // 此处编写初始化逻辑 this.player.id = domId; this.player.config = Object.assign({}, config, extraOptions); // 按你的调用逻辑返回player对象 return this.player; } }
方案2:类箭头函数属性
利用类箭头函数属性自动继承外层this,无需手动绑定,写法更简洁:
class NewPlayer { constructor() { this.player = {}; } // 箭头函数的this永远指向当前实例,无需额外绑定 init = (domId, config, extraOptions) => { this.player.id = domId; this.player.config = Object.assign({}, config, extraOptions); return this.player; } }
调用验证
两种方案都支持你需要的调用逻辑:
const myConfigObj = { autoplay: true, controls: false }; // 第一步获取init方法 let myPlayer = new NewPlayer().init; // 第二步直接调用方法初始化 let player = myPlayer('id', myConfigObj, {}); console.log(player); // 输出:{ id: 'id', config: { autoplay: true, controls: false } }
内容的提问来源于stack exchange,提问作者benntyGoodla
相关产品推荐
相关产品推荐

