美文网首页
Javasript中各种状态下的this指向

Javasript中各种状态下的this指向

作者: visitor009 | 来源:发表于2018-01-29 08:39 被阅读0次

据我所知的有5种:
1.作为普通函数调用:this指向全局
2.作为对象的方法调用:this指向当前对象
3.作为构造器使用: this指向实例对象
4.用call、apply调用时:this指向所指定的上下文
5.在箭头函数中使用this时:this指向箭头函数开始定义的上下文

作为普通函数调用

function test () {
    return this;
}
function test2 () {
    console.log(test());
}
let obj = {
    test: function() {
        console.log(test());
    }
}
console.log(test()); // window
test2(); // window
obj.test(); //window

作为对象的方法调用

let obj = {
    test: function() {
        return this;
    }
}
console.log(Object.is(obj, obj.test())); // true

作为构造函数调用

function Fn (num) {
    this.age = num;
}
let fn = new Fn(10);
let fn2 = new Fn(11);
console.log(fn.age); // 10
console.log(fn2.age); // 11

使用call、apply调用

window.str = 'window';
let obj = {
    str: 'obj',
}
function test () {
    test.str = 'test';
    console.log(this.str);
}
test(); // 普通调用,this执行window, 输出window
test.call(obj); // obj
test.call(test); // test

箭头函数的this

var fn = () => this; // 在全局下定义
function test () {  // 在全局下定义
    return this;
}
let obj = {
    fn: fn,  // 在obj对象中使用
    test: test,  // 在obj对象中使用
}
console.log(Object.is(obj.fn(), window)); // true
console.log(Object.is(obj.test(), obj)); // true

相关文章

  • Javasript中各种状态下的this指向

    据我所知的有5种:1.作为普通函数调用:this指向全局2.作为对象的方法调用:this指向当前对象3.作为构造器...

  • javasript中“==”与“===”的区别

  • 事件委托

    JavaScript事件代理和委托(Delegation) 在javasript中delegate这个词经常出现,...

  • JavaSript

    JavaScript特点 安全性(不允许直接访问本地硬盘),它可以做的就是信息的动态交互。 跨平台性。(只要是可以...

  • JavaScript几个小技巧

    &&、||运算的高级用法   在JavaSript中,“&&”运算符除了可以对布尔值进行与(AND)运算之外,还可...

  • 简述JS中的event delegate

    在javasript中delegate这个词经常出现,看字面的意思,代理、委托。 什么是delegate?我们为什...

  • iOS模拟各种网络状态(Xcode9)

    在iOS开发中我们有在各种不同网络状态下测试app运行状态的需求。苹果给我们提供了在模拟器和真机状态下,模拟各种网...

  • iOS模拟各种网络状态

    在iOS开发中我们有在各种不同网络状态下测试app运行状态的需求。苹果给我们提供了在模拟器和真机状态下,模拟各种网...

  • speaking of javasript

    引用方法 Referring to methods «Constructor».prototype.«method...

  • JS中this的指向和改变this指向

    this的指向 1.直接调用,指向window 2.在函数里调用,指向window 3.在构造函数里用new调用,...

网友评论

      本文标题:Javasript中各种状态下的this指向

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