javaScript中的this作用域

javaScript中的this作用域

  javaScript中的this作用域java的区别是,java中的this是在编译中确定,

     javaScript中的this是在运行时确定的,不同的调用方式,决定js中的this指向不同的对象。

代码实现:

  //this作用域
  function sayName(){
    console.log(this.name);
    console.log(this ===d1);
    console.log(this ===d2);
    console.log(this ===window);

  }
  sayName();

  function Person(name,age){
    this.name = name;
    this.age = age;
    this.sayName = sayName;
  }

  var d1 = new Person("ricky",24);
    d1.sayName();

    var d2 = new Person("rose",24);
  d2.sayName();

执行:sayName();时,这句打印的值为true  console.log(this ===window);

执行:d1.sayName();时,这句打印的值为true  console.log(this===d1);

执行:d2.sayName();时,这句打印的值为true  console.log(this ===d2);

 

原文地址:https://www.cnblogs.com/qqpw/p/6617311.html