您的位置:首頁技術文章
文章詳情頁

javascript - es6箭頭函數和this

瀏覽:110日期:2023-04-12 13:37:07

問題描述

const Title=React.createClass({ getDefaults: ()=> { return{ title:’hello world’ } }, render:()=>{ return <h1>{this.props.title}</h1> } }) ReactDOM.render( <Title/>, document.getElementById(’app6’) )此種情況下報錯:Cannot read property ’props’ of undefined

**請問:

(1)此種情況下箭頭函數和this是否可以一起使用?(2)如果可以一起使用請問有何種解決方法?**

問題解答

回答1:

可以改成

render() { console.log(this);}回答2:

萬惡的ES2015!!!給你翻一下。

function template(config) { var self = this; Object.keys(config).forEach(function (key) { self[key] = config[key]; });}function factory() {}factory.create = function (config) { return new template(config);}var instance = factory.create({ title: ’instance1’, method: () => { console.log(this); }});instance.method();

function template(config) { var self = this; Object.keys(config).forEach(function (key) { self[key] = config[key]; });}function factory() {}factory.create = function (config) { return new template(config);}var instance = factory.create({ title: ’instance1’, method() { console.log(this); }});instance.method();

基礎多看看,其實理解并不難

標簽: JavaScript
相關文章:
国产综合久久一区二区三区