zoukankan      html  css  js  c++  java
  • 方法中的函数会掩盖this,解决办法!

    要知道在javascript中this是种很神奇的东西,但是有时候也很淘气;

    如下:

    <script>
        var obj = {
            name: 'tqt',
            friends: ['shangs', 'lisi'],
            sayHello: function() {
                this.friends.forEach(function(friend){
                    console.log(this.name + ' say hello to ' + friend);
                });
            },
        }
        obj.sayHello();
        //say hello to shangs
        //say hello to lisi
    </script>

    此时this已经不再指向obj了所以不会有name属性;(this现在指向window,太淘气了!)

    对于这种情况解决办法如下:

    方法一: 

    <script>
        var obj = {
            name: 'tqt',
            friends: ['shangs', 'lisi'],
            sayHello: function() {
                var that = this;
                this.friends.forEach(function(friend){
                    console.log(that.name + ' say hello to ' + friend);
                });
            },
        }
        obj.sayHello();
        //tqt say hello to shangs
        //tqt say hello to lisi
    </script>

    方法二:

    <script>
        var obj = {
            name: 'tqt',
            friends: ['shangs', 'lisi'],
            sayHello: function() {
                this.friends.forEach(function(friend){
                    console.log(this.name + ' say hello to ' + friend);
                }.bind(this));
            },
        }
        obj.sayHello();
        //tqt say hello to shangs
        //tqt say hello to lisi
    </script>

    方法三:

    <script>
        var obj = {
            name: 'tqt',
            friends: ['shangs', 'lisi'],
            sayHello: function() {
                this.friends.forEach(function(friend){
                    console.log(this.name + ' say hello to ' + friend);
                }, this);
            },
        }
        obj.sayHello();
        //tqt say hello to shangs
        //tqt say hello to lisi
    </script>
  • 相关阅读:
    EasyUI datagrid动态加载json数据
    Java缓存机制
    爬虫入门 手写一个Java爬虫
    java解决前后台跨域问题
    HttpUrlConnection 基础使用
    聊聊spring-boot-starter-data-redis的配置变更
    Linux命令: 结束命令
    Linux其他: GitBash
    Python: 字典dict: 相同点
    Python: 字典dict: zip()
  • 原文地址:https://www.cnblogs.com/tqt--0812/p/6880491.html
Copyright © 2011-2022 走看看