zoukankan      html  css  js  c++  java
  • 关于js中this的理解和作用

    1、在全局代码中的this是指向全局对象,在浏览器中是window

    alert(this)

    2、只是作为单纯的函数进行调用

    function fooCoder(x) {  
        this.x = x;  
      }  
      fooCoder(2);  

    在普通函数中的this,指向了全局函数,即window,在严格模式下,是undefined

    3、作为对象的方法调用

    var name = "clever coder";  
    var person = {  
        name : "foocoder",  
        hello : function(sth){  
            console.log(this.name + " says " + sth);  
        }  
    }  
    person.hello("hello world");

    输出 foocoder says hello world。this指向person对象,即当前对象

    4、作为构造函数

    new FooCoder(); 

    函数内部的this指向新创建的对象

    5、内部函数

    var name = "clever coder";  
    var person = {  
        name : "foocoder",  
        hello : function(sth){  
            var sayhello = function(sth) {  
                console.log(this.name + " says " + sth);  
            };  
            sayhello(sth);  
        }  
    }  
    person.hello("hello world");//clever coder says hello world 

    在内部函数中,this没有按预想的绑定到外层函数对象上,而是绑定到了全局对象。这里普遍被认为是JavaScript语言的设计错误,因为没有人想让内部函数中的this指向全局对象。一般的处理方式是将this作为变量保存下来,一般约定为that或者self:

    var name = "clever coder";  
    var person = {  
        name : "foocoder",  
        hello : function(sth){  
            var that = this;  
            var sayhello = function(sth) {  
                console.log(that.name + " says " + sth);  
            };  
            sayhello(sth);  
        }  
    }  
    person.hello("hello world");//foocoder says hello world 

    6、使用apply和call设置this

    person.hello.call(person, "world")
  • 相关阅读:
    分布式算法(一致性Hash算法)
    浅析Postgres中的并发控制(Concurrency Control)与事务特性(上)
    PostgreSQL内核分析——BTree索引
    源码安装postgresql数据库
    QEMU漏洞挖掘
    mysql远程连接数据库
    C++学习之路(十一):C++的初始化列表
    搭建本地git服务器
    C++面试常见问题
    SkipList 跳表
  • 原文地址:https://www.cnblogs.com/Roxxane/p/14701087.html
Copyright © 2011-2022 走看看