美文网首页
this keyword - javacript

this keyword - javacript

作者: Zihowe | 来源:发表于2017-08-08 15:30 被阅读3次

javascript是万物皆对象,所以整个browser也是个object,可以用window指代也可以用this

A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.

function f1() {
  return this;
}
// In a browser:
f1() === window; // the window is the global object in browsers

// In Node:
f1() === global;

在非strict mode,不使用call, apply的话,this指代上一层对象。

// An object can be passed as the first argument to call or apply and this will be bound to it.
var obj = {a: 'Custom'};

// This property is set on the global object
var a = 'Global';

function whatsThis(arg) {
  return this.a;  // The value of this is dependent on how the function is called
}

whatsThis();          // Returns 'Global'
whatsThis.call(obj);  // Returns 'Custom'
whatsThis.apply(obj); // Returns 'Custom'
function add(c, d) {
  return this.a + this.b + c + d;
}

var o = {a: 1, b: 3};

// The first parameter is the object to use as
// 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as
// 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34

References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

相关文章

网友评论

      本文标题:this keyword - javacript

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