Example tutorial on the usage of This in javascript

零下一度
Release: 2017-06-25 09:38:12
Original
1406 people have browsed it

I have read the book "JavaScript You Don't Know" several times. It seems that every time I read it, I make new discoveries. Some of the content cannot be understood at once, but I seem to understand some concepts every time I read it.
Reread thethiskeyword again. The concept is very flexible and very difficult to grasp, so I see no harm in reading it often. I hope that JavaScript will be popular in the world, so the cost of learning will be low!
Refer to Chapter 1 and Chapter 2 of the second part of this book.

This keyword is one of the most complex mechanisms in js. It is automatically defined in the scope of all functions.

It seems that I also took a long detour in the process of learning this keyword. You have to ask me why I took a long detour. The key point is that I still haven’t thoroughly learned and understood the core concepts. This is no different from primary school students learning new knowledge. If you want to master the keyword this, you need to stick to the key concepts and don't imagine what this is all about.

Key concept: When a function in js is called, it must, must, be bound to an object. When analyzing the this keyword, you must know what the object is when the function is called. who is it? .
Remember: There is no relationship between the call and the definition of a function in js. The object bound to the function cannot be known until it is called.

The uncertainty of this keyword is a double-edged sword. One is the uncertainty of the object when the function is called. The use of functions in js is very flexible. Each object can borrow other functions. to complete the function. Second, this also caused some problems in learning this. So when learning, you must first understand the advantages of this keyword, and then go to learn the places that cause trouble

First look at the first piece of code
page 75

//注意只是定义了一个函数,并未调用,这时候函数是没有绑定任何对象function identify() {return this.name.toUpperCase(); }//同上面的函数,但是这个函数内部有点复杂,如果下面的代码看不懂//可以只看上面的函数function speak() {var greeting = "Hello, I'm " + identify.call( this );console.log( greeting ); }var me = { //定义了一个字面量对象 name: "Kyle" };var you = {//定义了一个字面量对象 name: "Reader" };//通过call方式把函数identify分别绑定到两个对象上//这时的this是指向me对象,和you对象 identify.call( me ); // KYLE identify.call( you ); // READER//通过call方式把函数call分别绑定到两个对象上//这时的this是指向me对象,和you对象 speak.call( me ); // Hello, I'm KYLE speak.call( you ); // Hello, I'm READER
Copy after login

When defining a function in JavaScript, the function does not belong to any object. This is very critical, very critical, very critical. This is the first obstacle to understanding this keyword.

The uncertainty of this keyword when defining js functions makes the use of js functions extremely flexible, and any object can use it.

What is this?

The binding of this has nothing to do with the location of the function definition, it onlydepends on the way the function is called.
When a function is called in javascript, an activity will be created Record (sometimes called context). This record includes where the function was called, the calling method of the function, and the parameters passed in. this is an attribute in the record.

The first problem when learning javascript keywords is to solve how to know the calling position of the function.

js object binding rules

Every When calling a js function, you must find an object, which can only be used after

binding. This is the largest concept that needs to be mastered after understanding the difference between the definition and calling of js functions. There are four binding methods in js. Personally speaking, binding rules is not difficult,The difficulty lies in understanding the function scope of js. Especiallydefault binding. This binding method is extremely confusing.

Default binding

This is an independent call of the function, that is, when a function is directly called, it does not seem to be bound to the object, but according to the previous introduction, in js Function calls must be bound to an object.

Look at the code below page 83

function foo() { //这是函数的定义位置console.log( this.a ); } var a = 2;//这个变量定义的含义是什么呢?仅仅是赋值给a吗? foo(); // 2 //这是函数的调用位置。为什么会打印出2呢?
Copy after login

Many functions are called like this. You can also write them in a similar way, but it is different if you understand the specific meaning.

The foo function is defined in the global scope (window scope). Coincidentally, its call is also in the global scope. Note that this is just a coincidence. So why does the value of variable a print out when foo() is called? Although the keyword var is used, we can know from the scope analysis that the variable a is actually a global variable. To put it more clearly, a is actually an attribute of the global object window, and 2 is the attribute value of this attribute.
When foo() is called, it is completely naked. It is just the function itself without any modifiers. At this time, it does not have any function wrapper and is under the global scope, so this in foo() points to For global objects, when you want to print this.a, you will find the global scope when you look for the call location of foo(). When you look for the attribute this.a of the global scope, you will print out the attribute value 2.

When we use the setTimeout and setInterval functions, these two functions are actually naked and are also bound to the window object.

Implicit binding

The function has modifiers added when it is called. Look at the code below

page 85

function foo() { //定义在全局作用下的函数,仅仅是定义,不是调用位置console.log( this.a ); }var obj = { //定义一个对象 a: 2,foo: foo }; obj.foo(); // 2 给foo()函数找了一个对象,this就指向这个对象了
Copy after login

This is the most common way. If you don’t write the previous obj, will it be the default binding above?

Implicit lossYou often see the sentence

var that=this; //这是什么含义
Copy after login

at the beginning of the outer function in the nested callback function of js code. Maybe you already know how to use it. But if you understand the meaning, you will be more comfortable using it

看下面段代码.这段代码其实以前我也不太理解,问题还是没有彻底领悟js函数定义和调用之间是没有关系的这一点。
page 86

function foo() { //定义了一个函数console.log( this.a ); }var obj = { //定义了一个对象字面量 a: 2,foo: foo //函数作为对对象的属性 };var bar = obj.foo; //把obj对象的函数foo属性赋值给bar变量//这里就是理解这个问题的关键,如果你现在认为调用bar()的时候绑定的对象//是obj那就完全搞错了。这个时候仅仅是把函数foo赋值给了var变量,//并没有把对象也给bar变量,因为这里还不是foo()函数的调用位置,现在//foo函数还没有绑定对象,那么调用bar()的时候对象到底是谁?不知道。//调用的时候才知道。var a = "oops, global"; // 任然是全局对象的属性 bar(); // "oops, global" 这里执行的是默认绑定,this就是去全局对象啦
Copy after login

下面这段代码就是使用var that=this的场景
在使用回调函数的时候要留心。js中函数是一等对象,可以作为另一个函数的参数传入函数。 问题就出在这里了,函数一旦作为实参代替形参的时候,实际也执行了和上面代码一样的赋值过程,实际只是传递了函数本身,原先的对象就没有了。

page 86

function foo() { //定义一个函数console.log( this.a ); }function doFoo(fn) { //fn是形参// 如果函数作为实参传入相当于代码 var fn=obj.foo//和上面一段代码是完全一样的,只是函数本身,并没有绑定任何对象 fn(); // 在这里调用的时候,由于fn只代表foo()函数,被绑定到全局对象上了 }var obj = {a: 2,foo: foo };var a = "oops, global"; // `a` also property on global object doFoo( obj.foo ); // "oops, global"不要被obj.foo迷惑了//没有实际执行函数的调用,此时obj.foo仅仅代表没有绑定任何对象的函数//这个代码块看着眼熟么?这就是javascript中回调函数的样子,当//一个函数作为参数传递进另一个函数的时候,这个参数函数就找不到自己绑定的对象是谁了,//所以就默认绑定到全局对象上了。但是我们既然在一个函数里调用另一个函数,肯定是要用这个函数操作当前的对象,那么既然找不到了,我们就手动给他指定一个对象吧。这就是为什么要使用//var that=this的原因。我觉得理解这个概念,js的功力至少会增加5%
Copy after login

The above is the detailed content of Example tutorial on the usage of This in javascript. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!