Home > Web Front-end > JS Tutorial > This mechanism in JavaScript_Basic knowledge

This mechanism in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:16:51
Original
1235 people have browsed it

JavaScript has its own set of this mechanism. In different situations, the pointing of this is also different.

Global scope

console.log(this); //全局变量
Copy after login

The global scope uses this to point to global variables, which is window in the browser environment.

Note: ECMAScript5’s strict mode does not have global variables, and this here is undefined.

Function calling

function foo() {
  console.log(this);
}

foo(); //全局变量

Copy after login

This in function calls also points to global variables.

Note: ECMAScript5’s strict mode does not have global variables, and this here is undefined.

Object method call

var test = {
  foo: function () {
    console.log(this);
  }
}

test.foo(); //test对象

Copy after login

In object method calls, this points to the caller.

var test = {
  foo: function () {
    console.log(this);
  }
}

var test2 = test.foo;
test2(); //全局变量

Copy after login

However, due to the late binding feature of this, in the above example, this will point to the global variable, which is equivalent to calling the function directly.

This is very important. The same code segment can only be determined when running

Constructor

function Foo() {
  console.log(this);
}

new Foo(); //新创建的对象
console.log(foo); 

Copy after login

Inside the constructor, this points to the newly created object.

Explicitly set this

function foo(a, b) {
  console.log(this);
}

var bar = {};

foo.apply(bar, [1, 2]); //bar
foo.call(1, 2); //Number对象

Copy after login

When using the call or apply method of Function.prototype, this inside the function will be set as the first parameter passed in.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template