• [Javascript] this in Function Calls


    In most cases, the value of a function's this argument is determined by how the function is called. This lesson explains what thisrefers to when we call plain function. Marius points out how functions behave differently in strict and non-strict mode. "use strict"mode defaults this to undefined and prevents us from assigning values to undefined. We must call functions as a constructor to assign their this value correctly.

    "use strict";
    
    console.log(this === global)  // false, in REPL this === global
    console.log(this === module.exports) // true
    
    function Person(firstName, lastName) {
        console.log(this === global) // without 'use strict', true; with strict mode, false
        console.log(this === undefined) //without 'use strict', false; with strict mode, true
    }
    
    Person()

    Inside a function, 

    • strict mode, 'this' is undefined
    • without strict mode, 'this' is global
    "use strict";
    
    console.log(this === global)  // false, in REPL this === global
    console.log(this === module.exports) // true
    
    function Person(firstName, lastName) {
        console.log(this === global) // without 'use strict', true; with strict mode, false
        console.log(this === undefined) //without 'use strict', false; with strict mode, true
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    const person = new Person("Jane", "Doe");
    console.log(person);
    console.log(global.firstName); //undefined
    console.log(global.lastName); //undefined
  • 相关阅读:
    #Leetcode# 448. Find All Numbers Disappeared in an Array
    #Leetcode# 65. Valid Number
    #Leetcode# 37. Sudoku Solver
    #Leetcode# 25. Reverse Nodes in k-Group
    POJ 3264 Balanced Lineup
    HDU 3947 Assign the task
    Codeforces Round #546 (Div. 2)
    2019.08.18【NOIP?提高组】模拟 A 组 总结
    jzoj 6307. 安排
    jzoj 6305. 最小值
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8023382.html
Copyright © 2020-2023  润新知