extend方法中for(const key in from)取不出类内定义的方法,但是可以调用
来源:9-1 合并配置的设计与实现 - 需求分析 + 默认配置

银狐tjfox
2019-10-19
老师,看了你的教程,跟着做,然后就弄了个react练手,但是在写的过程中用的extend这个方法时出了个问题,就是for(const key in from)里无法拿出from里面的方法名,请问老师这个是什么问题,我用的create-react-app脚手架,下面我把代码贴出来,请老师指导一下
package.json
{
"name": "thumbtack-web",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/jest": "24.0.19",
"@types/node": "12.11.1",
"@types/qs": "^6.5.3",
"@types/react": "16.9.7",
"@types/react-dom": "16.9.2",
"@types/react-router-dom": "^5.1.0",
"antd-mobile": "^2.3.1",
"axios": "^0.19.0",
"babel-plugin-import": "^1.12.2",
"customize-cra": "^0.8.0",
"http-proxy-middleware": "^0.20.0",
"less": "^3.10.3",
"less-loader": "^5.0.0",
"node-sass": "^4.12.0",
"qs": "^6.9.0",
"react": "^16.10.2",
"react-app-rewired": "^2.1.3",
"react-dom": "^16.10.2",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0",
"sass-loader": "^8.0.0",
"tslint": "^5.20.0",
"tslint-config-prettier": "^1.18.0",
"tslint-config-standard": "^8.0.1",
"typedoc": "^0.15.0",
"typescript": "3.6.4"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
tsconfig.json(说起这个,还有个小问题,create-react-app的这个compilerOptions在一运行yarn start的时候,不管你怎么改的,都会被重写,然后你改的就失效了,这是怎么做到的,有没有什么方法可以改呢?)
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
],
"exclude": [
"src/setupProxy.js"
]
}
index.tsx
declare global {
interface Window {
customReturnClickFunc?: () => void
}
}
interface ClickFunc {
(): void;
}
class ReturnClickFunc {
test: string = '123'
a() {
console.log(this);
}
addCustomReturnClickFunc(clickFunc: () => void) {
if (clickFunc) {
window.customReturnClickFunc = clickFunc;
}
}
doClick() {
if (window.customReturnClickFunc) {
window.customReturnClickFunc();
window.customReturnClickFunc = undefined;
} else {
window.history.back();
}
}
}
class Return {
func?: ClickFunc & ReturnClickFunc;
}
/**
* 这个方法里面key无论如何也拿不出来,导致在外部像调用addCustomReturnClickFunc无法被调用
*/
function extend<T, U>(to: T, from: U): T & U {
for (const key in from) {
console.log(key);
(to as T & U)[key] = from[key] as any;
}
return to as T & U;
}
let context = new ReturnClickFunc();
let click = ReturnClickFunc.prototype.doClick.bind(context);
Return.prototype.func = extend(click, context);
export { Return }
写回答
1回答
-
ustbhuangyi
2019-10-19
你有单步调试过吗?
042019-10-22
相似问题