欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  在全局作用域中声明的任何变量和函数默认都是作为window对象的属性而存在的
 
  this是在函数执行的过程中自动创建的一个指向一个对象的内部指针,this的指向不是固定的,会根据调用的不同,而指向不同的地方。
 
  两个方向
 
  1. 全局作用域中使用this
 
  全局作用域中使用this,也就是说不在任何函数体内部使用this,那么这个时候this就是指的 window。
 
  2. 函数中this的指向
 
  A. 非构造函数中this指向
 
  非构造函数中this指向的就是调用这个方法的那个对象
 
  B. 构造方法中的this指向
 
  构造方法中的this指代的是未来要创建的那个对象。
 
  其实用new调用构造函数的时候,构造函数内部其实有个默认的 return this; 这就是为什么this指代那个要创建的对象了
 
  this的指代和代码出现的位置无关,只和调用这个方法的对象有关。
 
  <!--//全局使用this-->
 
  <script type="text/java">
 
  console.log("全局使用this");
 
  this.num = 100; //向this指代的对象中添加一个属性 num, 并让属性的值为100
 
  window.num = 200; // 在全局作用域中因为this就是window,所以这时是在修改属性num的值为200
 
  console.log(this === window); // true this就是指向的window对象,所以两者是是恒等
 
  console.log(this.num); //200
 
  console.log(window.num); //200
 
  </script>
 
  <!--非构造函数this1-->
 
  <script type="text/java">
 
  console.log("非构造函数使用this1")
 
  function test() {
 
  console.log(this == window);
 
  this.age = 20;
 
  }
 
  test(); //其实是 window.test(); 所以这个时候test中的this指向window
 
  </script>
 
  <!--//非构造函数this2-->
 
  <script type="text/java">
 
  console.log("非构造函数使用this2");
 
  var p = {
 
  age : 20,
 
  sex : "女",
 
  sayAge: function (argument) {
 
  console.log(this.age);
 
  console.log(this === window);//false
 
  console.log(this === p);//true
 
  }
 
  }
 
  p.sayAge();//调用对象p的方法sayAge() 所以这个时候this指向的是 p 这个对象
 
  </script>
 
  <!--构造函数使用this-->
 
  <script type="text/java">
 
  console.log("构造函数this指向");
 
  function Person () {
 
  this.age = 20;
 
  return this; //作为构造函数的时候,这个行代码默认会添加
 
  }
 
  var p1 = new Person();//这个时候 Person中的this就是指的p1
 
  var p2 = new Person(); //这是时候 Person中的this就是知道p2
 
  </script>

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h62788.shtml