1. 函數的this是什麼?
-- 任何函數本質上都是通過某個物件來調用的,如果沒有指定就是window
-- 所有函數內部都有一個變量this
-- this的值是調用函數的當前物件
2. 如何確定this的值?
-- fn(): window
-- p.fn()p
-- new fn():新建立的物件
-- p.call(obj)obj

 

<script type="text/javascript">
 function Person(color) {
  console.log(this);
  this.color = color;

  this.getColor = function () {
   console.log(this);
   return this.color;
  };

  this.setColor = function (color) {
   console.log(this);
   this.color = color;
  };
 }

 Person("red"); // this是誰? window

 const p = new Person("yellow"); // this是誰?p

 p.getColor(); //this是誰?p

 const obj = {};
 p.setColor.call(obj, "black"); // this是誰?obj

 const test = p.setColor;
 test(); // this是誰?window

 function fun1() {
  function fun2() {
   console.log(this);
  }

  fun2(); // this是誰?window
 }

 fun1();

</script>
arrow
arrow
    文章標籤
    JavaScript 函數 this
    全站熱搜

    bingzhichen 發表在 痞客邦 留言(0) 人氣()