搜索

首页  >  问答  >  正文

javascript - es6箭头函数和this

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<code> 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

 

</code>

**请问:

1

2

<code>(1)此种情况下箭头函数和this是否可以一起使用?

(2)如果可以一起使用请问有何种解决方法?**</code>

迷茫迷茫2811 天前773

全部回复(2)我来回复

  • 巴扎黑

    巴扎黑2017-07-05 10:39:12

    可以改成

    1

    2

    3

    <code>render() {

        console.log(this);

    }</code>

    回复
    0
  • PHP中文网

    PHP中文网2017-07-05 10:39:12

    万恶的ES2015!!!
    给你翻一下。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    <code>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();</code>

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    <code>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();</code>

    基础多看看,其实理解并不难

    回复
    0
  • 取消回复