美文网首页
JS this指向

JS this指向

作者: 苏码码 | 来源:发表于2021-04-10 17:56 被阅读0次
window.onload = function() {
 // this指向
  // 简单函数
  function f() {

    //  console.log(this)  // 在非严格模式下 this => window
    //  "use strict"
    console.log(this) // 在严格模式下 this => undefiend
  }
  f()

  // 内置函数中 this => window
  setTimeout(f, 1000)

  // 回调函数 -- 一个函数被当做参数传递给另一个函数
  // this => window
  function test(v) {
    console.log(v)
  }

  function f2(callBack,v) {
    callBack(v)
  }

  f2(test, 'hello')

  // 另一种写法
  f2(function(v){console.log(v)},'world')
  // this => window
  f2(function(v){console.log(this)},'world')

  // 数组  this指向调用者
  function f3() {
    console.log(this)
  }
  var arr = [f3, 4,5,6]
  arr[0]()  // this -> [ƒ, 4, 5, 6]  this指向arr

  var f = arr[0]
  f()  // this => window


  // 对象
  var obj = {}
  obj.id = 123
  obj.init = function() {
    console.log(this)
  }
  obj.init()  // this => obj


  // 构造函数
  function Fun(name,age) {
    this.name = name
    this.age = age
    this.action = function() {
      console.log(this)
    }
  }
  var fun2 = new Fun('abc',17)
  fun2.action() // this指向的是新创建的对象,而不是构造函数本身

  var fun3 = new Fun('asd',27)
  fun3.action()


  // 如何改变this的指向  apply()  call()   bind()

  var a = 10
  function f5(x1, x2) {
    return this.a + x1 + x2
  }

  var obj5 = {
    a: 100,
    action: f5
  }
  console.log(obj5.action(1,2)) // 103 this指向 obj5

  console.log(obj5.action.apply(window,[1,2])) // 13 this指向window  全局

  console.log(obj5.action.call(window,1,2)) // 13 this指向window

  //  bind() 绑定this 也是改变作用域  绑定后不能再改变this的指向
  var obj6 = {
    a: 1000
  }
  var a8 = f5.bind(obj6,1,2)
  a8() // 1003
}

相关文章

  • JS this指向

    一、js中的四种调用模式s 构造函数调用:new Foo(); 对象方法调用:o.method(); 函数直接调用...

  • js this指向

    this指向调用该函数的对象 在函数中this到底取何值,是在函数真正被调用执行的时候确定的,函数定义的时候确定不...

  • JS this指向

    首先,请牢记以下三点1. this指向的,只可能是对象!2.this指向谁,不取决于this写在哪!而是取决于函数...

  • JS this指向

  • JS进阶篇-this指向问题

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

  • java 有关this,apply使用

    js的call js的this指向改变 使用 java 的 apply

  • js:this指向问题

    var 作用域 先来看个简单的例子: 直觉地,内部函数可以访问外部函数的变量,外部不能访问内部函数的变量。上面的例...

  • JS中this指向

    一、全局作用域中的thises5与es6中严格模式与非严格模式全局函数的this都指向window 二、全局作用域...

  • JS中this指向

    函数有4种调用方式,对应就有4种绑定规则:默认绑定、隐式绑定、硬绑定和构造函数绑定。 1、默认绑定 当作为普通函数...

  • JS—-this指向(一)

    没有箭头函数之前,我们说this就是函数运行时所在的环境对象,但是在箭头函数中this就是定义时所在的对象,先说大...

网友评论

      本文标题:JS this指向

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