JS中的this是用来干什么的

Yang 186

javascript中this的用法主要有以下几点:一、在一般函数方法中使用this指代全局对象;二、作为对象方法调用,this指代上级对象;三、作为构造函数调用,this 指代new 出的对象;四、apply 调用 。

一、在一般函数方法中使用this指代全局对象

function test(){

    this、x = 1;

    alert(this、x);

  }

  test(); // 1

二、作为对象方法调用,this指代上级对象

function test(){

  alert(this、x);

}

var o = {};

o、x = 1;

o、m = test;

o、m(); // 1

三、作为构造函数调用,this 指代new 出的对象

function test(){

  this、x = 1;

}

var o = new test();

alert(o、x); // 1

  //运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:

var x = 2;

function test(){

  this、x = 1;

}

var o = new test();

alert(x); //2

四、apply 调用

apply方法作用是改变函数的调用对象,此方法的名列前茅个参数为改变后调用这个函数的对象,this指代名列前茅个参数

  var x = 0;

  function test(){

    alert(this、x);

  }

  var o={};

  o、x = 1;

  o、m = test;

o、m、apply(); //0

延伸阅读

This的五种用法

1、方法中的this

在对象方法中,this指的是此方法的“拥有者”。

this代表person对象

 var person = {

            firstName:”Bill”,

            lastName:”Gates”,

            id:678,

            fullName:function(){

                return this、firstName + ” ” + this、lastName;

            }

        };

2、单独的this

(1)在单独使用时,拥有者是全局对象,this指的是全局对象

在浏览器窗口中,全局对象是[object Window]:

 var x = this;

 document、getElementById(“demo”)、innerHTML = x;

(2)在严格模式中,如果单独使用,那么this指的是全局对象[object Window]:

“use strict”;

var x = this;

3、函数中的this(默认)

在js函数中,函数的拥有者默认绑定this、

因此,在函数中,this指的是全局对象[object Window]

function myFunction(){

    return this;

    }

4、函数中的this(严格模式)

js严格模式不允许默认绑定,因此,在函数中使用时,在严格模式下,this是未定义的undefined

“use strict”;

function myFunction(){

    return this;

}

5、事件处理程序中的this

this指的是html元素,如下面例子中,this指的是button

<button onclick = “this、style、display=’none’”>

     点击来删除我!

</button>

回复

我来回复
  • 暂无回复内容

注册PingCode 在线客服
站长微信
站长微信
电话联系

400-800-1024

工作日9:30-21:00在线

分享本页
返回顶部