第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將方法導(dǎo)出到類中的正確方法(原型?)

將方法導(dǎo)出到類中的正確方法(原型?)

慕桂英3389331 2021-11-12 10:48:52
我在重構(gòu)我的東西時遇到了一個小問題......問題:我得到了一個包含 1.1k 行和 ~10 個方法的類文件我想做的事情(tl;dr):將每個方法外包到它自己的文件中,module.export 它們,有一個需要所有這些的幫助方法/文件,讓我的類只導(dǎo)入這個幫助文件并將所有方法添加回我的類,以便 class.method 正確調(diào)用它們。我想做什么(有一點(diǎn)額外的)Aight - 狀態(tài)是這樣的……我有課我的類.jsclass MyClass{  constructor(a,b){    this.a = a    this.b = b  }  methodOne(){  console.log(this.a)  *100 lines of code*  }  methodTwo(){  *100 lines of code*  }  methodThree(){  *100 lines of code*  }   .... and so on}我想要什么:方法一.js module.exports.methodOne = () => {   console.log(this.a)    99 more lines of Code }方法二.js module.exports.methodTwo = () => {    100 lines of Code }...等等functions_injector.js - 長度有點(diǎn)偽const fs = require('fs')const functions = {}const functionsInjector = () => { fs.readDir('./functions/', (err, files) => {   files.each((fileName) => {   functions[fileName.split('.')[0]] = require('./functions/'+fileName)        }}functionsInjector()module.exports = functions我的類.jsconst functions = require('./functions_injector')class MyClass {  constructor(a,b) {    this.a = a    this.b = b }}const funcNames = Object.keys(functions)const funcs = Object.values(functions)funcNames.forEach((funcName, idx) => {  MyClass.prototype[funcName] = funcs[idx]}const tryMe = new MyClass('a', 'b)const plsWork = tryMe.methodOne()console.log(plsWork)預(yù)期:'a'但遺憾的是,現(xiàn)實(shí)是:未定義通過在 methodOne.js 中調(diào)用 console.log(this) 來深入挖掘一下,返回 {methodOne: [Function]) 有點(diǎn)道理。但由于這是通過調(diào)用的結(jié)果const tryMe = new MyClass()tryMe.methodOne()我至少可以確認(rèn),我可以通過類訪問這些方法,現(xiàn)在他們只需要訪問相同的this代碼稍微簡化了一點(diǎn)。真正的代碼是完全異步/等待等等,但我不想用更多代碼來打擾你。注入器的構(gòu)造并將其傳遞給 myClass 正在工作,我可以訪問 {name:function} 對的對象。是類的方法。非常感謝任何幫助!干杯PS:我可能可以讓每個方法成為它自己的類并擴(kuò)展和擴(kuò)展......不想走那條路...我還在考慮我是否在方法的 module.exports 方面做錯了什么。如果我這樣做了,我絕對沒有任何線索:D
查看完整描述

1 回答

?
月關(guān)寶盒

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個贊

此方法有效,但箭頭函數(shù)未綁定this,arguments因此無法訪問this.a或this.b


而且,您的MyClassit 中有一個錯字constructor。


簡單的概念證明:簡單的代碼示例:


const methodOne = function () {

  console.log(this.a);

}


class MyClass {

  constructor(a, b) {

    this.a = a;

    this.b = b;

  }

  m2() {

    console.log(this.b);

  }

}

MyClass.prototype.methodOne = methodOne;


const tryMe = new MyClass('I work', 'I work too');

tryMe.methodOne()

tryMe.m2();

輸出:


I work

I work too


查看完整回答
反對 回復(fù) 2021-11-12
  • 1 回答
  • 0 關(guān)注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號