Javascript中的 this指向问题

  1. 普通函数中 this指向window
  2. 对象的方法中 this指向当前对象
  3. 构造函数中 this指向构造函数的实例化对象
  4. 原型对象的方法中 this指向当前的实例对象
  5. 计时器中 this指向window
  6. 事件处理函数 this指向触发事件的对象

不理解的话,建议把代码拷贝下来,一个一个打开运行一遍。上代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>this的指向</title>
</head>
<body>
	<button id="btn">点我呀</button>
<script>
  // JavaScript中,this通常指向的是执行的函数本身,或者是函数所属的对象


  // 1. 普通函数中  this指向window
  // var a = 123;

  // function test() {
  //   var a = 456;
  //   console.log(this.a);  // 123
  // }

  // test();


  // 2. 对象的方法中  this指向当前对象
  // var obj = {
  // 	name: "haha",
  // 	say: function () {
  // 		console.log(this);
  // 	}
  // }
  // obj.say();


  // 3. 构造函数中  this指向构造函数的实例化对象
  // function Fn() {
  // 	this.name = "abc";
  // 	console.log(this);
  // }
  // var f = new Fn();


  // 4. 原型对象的方法中  this指向当前的实例对象
  //  function Test() {
  //    this.a = "123";
  //    this.b = "321";
  //  }
  //  Test.prototype.doing = function () {
  //    console.log(this);
  //  }
  //  var test = new Test();
  //  test.doing();


  // 5. 计时器中  this指向window
  //	var t = setTimeout(function () {
  //		console.log(this);
  //	},2000)


  // 6. 事件处理函数  this指向触发事件的对象
   // var btn = document.getElementById("btn");
   // btn.onclick = function () {
   //   console.log(this);
   //   console.log("叫你点就点,真乖~");
   // }



  // 题1:
  // var x = 2;
  // function test(){
  //  this.x = 1;
  // }
  // var o = new test();
  // console.log("o.x: " + o.x); // 1
  // o.x = 3;
  // test();                     // 普通函数指向window
  // x*=10;
  // console.log("o.x: " + o.x); // 3
  // console.log("x: " + x);     // 10


  // 题2:
  // function a(xx) {
  //   this.x = xx;
  //   return this;
  // };

  // var y = a(6);
  // console.log(y.x);// 6


  // 题3 (call apply bind):
  // var modal = {
  //   msg: 'aaa'
  // }
  // function showMsg() {
  //   console.log(this.msg);
  // }
  // // showMsg.call(modal); // 改变this指向到modal
  // // showMsg.apply(modal);
  // var newMsg = showMsg.bind(modal)
  // newMsg();

  // bind() 的作用:创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体。当新函数被调用时 this 值绑定到 bind()的第一个参数。

  
  // 题4(闭包):
  // var Foo = {};
  // Foo.method = function(){ 
  // 	  console.log(this);   // Foo
  //   var test = function(){
  //     console.log(this);   // window
  //   };
  //   test();
  // };
  // Foo.method();

</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值