指向如此神奇:揭示Js函数this的10个惊人事实!

this指向总结

定义函数中this,this指向window。如果是调用函数,指向函数实例

对象(包括json)中的this指向对象实例

for循环中,this指向最后一个循环值

异步操作中,this指向最终值

() => {}本身并没有this,this为父级代码继承过来的,不同情况下调用同一个函数,this指向不同,不一定指向对象实例本身

setTimeout时,function(){}要用_this,不能直接使用this,因为this指向函数本身

this指向实例

vue中data、computed、methods的调用
    this.age;
    this.newOption
    this.getData();

    this.$parent可以访问父级vue实例(或者组件)
    this.$root可以访问根级vue实例(或者组件)
    this.$el
    this.$data
    this.$router  访问当前的路由

var json1={
    fn1:function(){
        console.log(this);   //指向json
    },
    fn2:function(){
        var i=3;
        function fn3(){
            console.log(this)   //指向window
        };
        return  fn3();
    }
}

json1.fn1();
json1.fn2();

call()、apply()、bind()()三者的区别:改变this指向的三种方法

call():第一个参数:this指向,如果要传参,后面依次是参数
apply:第一个参数:this指向,第二个参数接受的是一个数组,如果要传参,后面依次放入数组中
bind():只改变this指向,不会调用函数。如果喜爱那个调用还需要加“()”,传参和跟call相似,只不过后面多了个 ()下面进入实体的案列

function fn(x,y){
   console.log(this);
}
var obj = {
   name:“zs“
}
fn(1,2);
fn.call(obj,1,2);

function fn(x,y){
   console.log(this);
}
var obj = {
   name:“zs“
}
fn(1,2);
fn.apply(obj,[1,2]);

function fn(x,y){
   console.log(this);
}
var obj = {
   name:“zs“
}
fn(1,2);
fn.bind(obj,1,2)();

免费的API接口开放平台

相关推荐

  1. 指向如此神奇揭示Js函数this10惊人事实

    2024-07-10 03:38:01       27 阅读
  2. 这是你不知道js函数this指向惊人之处!

    2024-07-10 03:38:01       27 阅读
  3. 【必读】HTML中BFC:10你不知道惊人事实

    2024-07-10 03:38:01       25 阅读
  4. 【前端学习——js篇】 10.this指向

    2024-07-10 03:38:01       35 阅读
  5. js中使用箭头函数以及setTimeout时this指向问题

    2024-07-10 03:38:01       25 阅读
  6. 箭头函数this指向问题

    2024-07-10 03:38:01       84 阅读
  7. 【vue回调函数 this 指向上】

    2024-07-10 03:38:01       37 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 03:38:01       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 03:38:01       107 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 03:38:01       90 阅读
  4. Python语言-面向对象

    2024-07-10 03:38:01       98 阅读

热门阅读

  1. k8s 使用 helm 文件部署 8.12.2 es 分角色集群

    2024-07-10 03:38:01       21 阅读
  2. 数据编码的艺术:sklearn中的数据转换秘籍

    2024-07-10 03:38:01       25 阅读
  3. android pdf框架-11,查看图片

    2024-07-10 03:38:01       22 阅读
  4. 深入探索:scikit-learn中递归特征消除(RFE)的奥秘

    2024-07-10 03:38:01       30 阅读
  5. 需求分析分类和层级、分析步骤

    2024-07-10 03:38:01       24 阅读
  6. js list to tree

    2024-07-10 03:38:01       20 阅读
  7. 02更新用户在线状态

    2024-07-10 03:38:01       22 阅读
  8. CSS魔法:link与@import的秘密较量

    2024-07-10 03:38:01       23 阅读
  9. 第12章:软件系统分析与设计

    2024-07-10 03:38:01       22 阅读
  10. Rust入门实战 编写Minecraft启动器#2建立资源模型

    2024-07-10 03:38:01       26 阅读
  11. three.js利用着色器实现波浪效果

    2024-07-10 03:38:01       25 阅读
  12. Python pdfplumber库:轻松解析PDF文件

    2024-07-10 03:38:01       28 阅读