美文网首页
js中的this指向问题和几道练习题

js中的this指向问题和几道练习题

作者: 哔哔_fc39 | 来源:发表于2019-04-02 19:15 被阅读0次

this规则


1.函数预编译过程,this指向window

var a = 5;
function test(){
    a=0;
    console.log(a);
    console.log(this.a);
    var a;
    console.log(a);
}
test();
console.log("---------------")
new test();
  • 答案
0
5
0
---------------
0
undefined
0
  • 解析

运行函数前,进行预编译。
1.test()时:

  GO:{
      a:5,
      test:function test
      this:window
  }
  AO:{
      a:0
  }
//执行test();时,this指向window

1.new test()时:

  GO:{
      a:5,
      test:function test
      
  }
  AO:{
      this:{}
      a:0
  }
//执行new test();时,AO会在后台生成this对象,所以this指向ao本身

2.全局作用域里,this指向window

3.call和apply可以改变this指向,区别时参数列表不一样。

4. obj.fun(); fun里的this指向obj。

 var obj = {
     a: function () {
         console.log(this.name)
     },
     name: 'aaabb'
 }
 obj.a();//aaabb
var name = "222"
var a = {
    name: "111",
    say: function () {
        console.log(this.name);
    }
}
var fun = a.say;
fun()//222;fun中的this指向window
a.say()//111;this指向a
var b = {
    name: "333",
    say: function (fun) {
        //this--->b
        
        fun();
        //运行fun()
        //但是不是this.fun()...是外面的那个fun
       
    }
}
b.say(a.say);//222 
b.say = a.say;
b.say();//333

如果搞懂了这题,就没多大问题了。

相关文章

  • js中的this指向问题和几道练习题

    this规则 1.函数预编译过程,this指向window 答案 解析 运行函数前,进行预编译。1.test()时...

  • JS进阶篇-this指向问题

    JS中this的指向问题不同于其他语言,JS中的this不是指向定义它的位置,而是在哪里调用它就指向哪里。 JS中...

  • js中this指向问题

    this的指向在函数定义的时候是无法确定的,只有函数执行的时候才能确定this到底指向谁,实际this指向是调用他...

  • JS中this指向问题

    首先声明,添加删除线的都是不太确定的 下面我们分情况解释: 1、函数调用模式--当一个函数并非一个对象的属性时,那...

  • js中this指向问题?

    This是一个关键字,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。 this 是在函数被调用时确...

  • js中this的指向问题

    this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用,下面分...

  • js 中 this 的指向问题

  • JS中的this指向问题

    1. this的几种绑定方法 (1)普通函数中的this指向函数的调用点 (2) call明确绑定 (3)bind...

  • JS 中的 this指向问题

    程序员就是没有人情味的原始人,不懂交际。谈不到对象。每天就是查看a-z,0-9加上!@#¥%…/&()+-=/<>...

  • js中的this指向问题

    只要记住这句话,谁调用的就指向谁,既调用函数所处的父层 window 对象 此时的this=>foo,如果改成这样...

网友评论

      本文标题:js中的this指向问题和几道练习题

      本文链接:https://www.haomeiwen.com/subject/crrnbqtx.html