Specific to the practical application ,this There are four kinds of directions :

  1. Method call as object

  2. Called as a normal function

  3. Constructor call

  4. apply and call call

Now we're going to dissect the front 3 spot , As for the 4 Dot apply and call call , Will be in call and apply Part of it explains in detail .

1. Method call as object

explain : When called as an object method ,this Point to the object . give an example :

 //1. Method call as object 
// When called as an object method ,this Point to the object . var obj = {
a: ,
getA: function {
console.log(this === obj);
console.log(this.a);
}
}; obj.getA; // true , 1

2. Called as a normal function

explain : When called as a normal function ,this Always point to global objects ( Browser is window). give an example :

 //2. Called as a normal function
// When not called as an object property ,this Must point to an object . That's the global object .
window.name = 'globalName';
var getName = function {
console.log(this.name);
}; getName; // 'globalName' var myObject = {
name: "ObjectName",
getName: function {
console.log(this.name)
}
};
myObject.getName; // 'ObjectName'
// This is essentially a function {console.log(this.name)}
// This sentence is assigned to theName.thisName Invokes in global objects , What is read naturally is the global object name value
var theName = myObject.getName;
theName; // 'globalName'

3. Constructor call

explain : When called as a constructor ,this Point to the returned object . give an example :

 // 3. Call as a constructor
// When called as a constructor ,this Point to the returned object .
var myClass = function {
this.name = "Lxxyx";
}; var obj = new myClass;
console.log(obj.name); // Lxxyx
console.log(obj) // myClass {name: "Lxxyx"}

But if... Is manually specified in the constructor return Other objects , that this Will not work . If return It's about other data types , No problem .

var myClass = function {
this.name = "Lxxyx";
// Join in return when , Other objects are returned .this It doesn't work .
return {
name:"ReturnOthers"
}
}; var obj = new myClass;
console.log(obj.name); // ReturnOthers

4. A deeper understanding from examples .

Example 1:

function a{
var user = " Dream chaser ";
console.log(this.user); //undefined
console.log(this); //Window
}
a;

As we said above this Finally, it points to the object that calls it , Functions here a It's actually being Window What the object points out , The following code can prove .

function a{
var user = " Dream chaser ";
console.log(this.user); //undefined
console.log(this); //Window
}
window.a;

Same code as above , Actually alert It's also window A property of , It's also window It was ordered .

Example 2:

var o = {
user:" Dream chaser ",
fn:function{
console.log(this.user); // Dream chaser
}
}
o.fn;

there this Point to the object o, Because you call this fn It's through o.fn Executive , That natural direction is the object o, Here's another point ,this The direction of a function cannot be determined when it is created , It can only be determined when calling , Whoever calls will point to who , Be sure to make this clear .

In fact, examples 1 And examples 2 It's not accurate enough , The following example can overturn the above theory .

If you want to understand it thoroughly this You have to look at the next few examples

Source of this article : Dream blog

Example 3:

var o = {
user:" Dream chaser ",
fn:function{
console.log(this.user); // Dream chaser
}
}
window.o.fn;

This code is almost the same as the one above , But here this Why not point to window, If you follow the above theory , Final this Point to the object that calls it , Let's start with something else ,window yes js Global object in , The variables we create are actually for window Add attribute , So you can use window spot o object .

I won't explain why the code above this Why didn't it point to window, Let's take another look at the code .

var o = {
a:,
b:{
a:,
fn:function{
console.log(this.a); //
}
}
}
o.b.fn;

It's the same thing here o It was ordered , But the same this Didn't execute it , Then you will say that what I said at the beginning is not all wrong ? It's not , It's just that it wasn't accurate at the beginning , Next I'll add , I'm sure you can fully understand this The problem of the direction of .

situation 1: If a function has this, But it's not called by the object at the next level , that this It points to window, What needs to be explained here is that js In the strict version of this It's not about window, But we don't discuss the strict version here , You want to know that you can search on the Internet by yourself .

situation 2: If a function has this, This function has been called by an object of a higher level , that this It points to the object at the next level .

situation 3: If a function has this, This function contains multiple objects , Although this function is called by the outermost object ,this It only points to the object at the next level , Example 3 Can prove that , If you don't believe it , So let's move on to a few examples .

var o = {
a:,
b:{
// a:12,
fn:function{
console.log(this.a); //undefined
}
}
}
o.b.fn;

Although the object b There are no attributes in a, This this It also points to objects b, because this It only points to its upper level object , Whether or not there is one in this object this things .

There is a special case , Example 4:

var o = {
a:,
b:{
a:,
fn:function{
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j;

here this Pointing to window, Is there something wrong ? It's because you don't understand a word , It's also crucial .

this Always pointing at the last object that calls it , That is to say, it depends on who called it when it was executed , Example 4 Although the function fn It's the object b The referenced , But in will fn Assign a value to a variable j It's not implemented at the time, so the final point is window, This and examples 3 It's different , Example 3 It's direct execution fn.

this In fact, that's the same thing , It's just that in different situations, it points to different things , In the summary above, there are some small mistakes in every place , It can't be said to be a mistake , It's different in different circumstances , So I can't explain it at one time , You can only experience it slowly .

Constructor version this:

function Fn{
this.user = " Dream chaser ";
}
var a = new Fn;
console.log(a.user); // Dream chaser

The reason for this is a You can point out functions Fn Inside user Because new Keywords can change this The direction of , Put this this Point to object a, Why do I say a It's the object , Because in the new Keyword is to create an object instance , To understand this sentence, consider our example 3, We use variables here a Created a Fn Example ( It's equivalent to making a copy of Fn To the object a Inside ), At this point, it's just creating , It's not implemented , And calling this function Fn It's the object a, that this Nature is the object a, So why the object Fn There will be user, Because you've made a copy Fn Function to object a in , It was used new Keywords are the same as copying a .

Apart from the above , We can also change on our own this The direction of , About self change this Look at the direction of JavaScript in call,apply,bind A summary of the methods in this article , It explains in detail how we can manually change this The direction of .

Update a little problem when this meet return when

function fn
{
this.user = ' Dream chaser ';
return {};
}
var a = new fn;
console.log(a.user); //undefined

Then look at one

function fn
{
this.user = ' Dream chaser ';
return function{};
}
var a = new fn;
console.log(a.user); //undefined

Come again

function fn
{
this.user = ' Dream chaser ';
return ;
}
var a = new fn;
console.log(a.user); // Dream chaser
function fn
{
this.user = ' Dream chaser ';
return undefined;
}
var a = new fn;
console.log(a.user); // Dream chaser

What does that mean ?

If the return value is an object , that this Point to the returned object , If the return value is not an object this Or an instance of a function .

function fn
{
this.user = ' Dream chaser ';
return undefined;
}
var a = new fn;
console.log(a); //fn {user: " Dream chaser "}

Another point is that although null Also object , But here this Or an instance of that function , because null A special .

function fn
{
this.user = ' Dream chaser ';
return null;
}
var a = new fn;
console.log(a.user); // Dream chaser

Knowledge points supplement :

1. Default... In strict version this No more window, It is undefined.

2.new The operator changes the function this Direction problem of , Although we explained above , But there is no in-depth discussion on this issue , It's rarely said on the Internet , So it's necessary to say .

function fn{
this.num = 1;
}
var a = new fn;
console.log(a.num); //1

Why? this Will point to a? First new Keyword will create an empty object , Then it automatically calls a function apply Method , take this Point to this empty object , In this case, the function inside this Will be replaced by this empty object

Call and Apply

Call and Apply It's the same thing . Are used to specify the body of a function this The direction of .

Call and Apply The difference between

Call: The first parameter is zero this The direction of , The parameters to be passed to the function have to be input one by one .Apply: The first parameter is zero this The direction of , The second parameter is an array , Pass in all parameters at once .

If the first parameter is null, be this Point to the call itself .

1. change this Point to

explain : This is a call and apply The most common use of . Used to change the body of a function this The direction of . give an example :

var name = "GlobalName"
var func = function {
console.log(this.name)
}; func; // "GlobalName" var obj = {
name: "Lxxyx",
getName: function {
console.log(this.name)
}
}; obj.getName.apply(window) // "GlobalName" take this Point to window
func.apply(obj) // "Lxxyx" take this Point to obj

2. Borrowing methods from other objects

Start with an anonymous function that executes immediately :

(function(a, b) {
console.log(arguments) //[1,2]
// call Array Prototype method of
Array.prototype.push.call(arguments, );
console.log(arguments) // [1,2,3]
})(,)

Function has arguments attribute , and arguments It's an array of classes .

however arguments You can't call array methods directly , So we're going to use call perhaps apply To call Array Prototype methods of objects .

And the principles are easy to understand , For example, what I just called is push Method , and push The method is in Google's v8 In the engine , The source code is like this :

function ArrayPush {
var n = TO_UINT32(this.length); // By push Length of object
var m = % _ArgumentsLength; // push The number of parameters
for (var i = ; i < m; i++) {
this[i + n] = % _Arguments(i); // Copy elements
}
this.length = n + m; // correct length attribute
return this.length;
}

It only works with this of , So as long as it's a class array object , You can call related methods to handle .

js One of the skills this,call,apply More articles about

  1. JS skill

    2016-08-09 200 Multiple js Trick code (Down) word download 200 Multiple js Trick code Catalog 1. Text box focus problem ... 6 2. Special colors for web buttons ... 6 3. The color changes as the mouse moves in and out ... ...

  2. js note —— understand js Medium call And apply

    call And apply stay js I can often touch it in the classroom , But I always feel strange , I can't use it skillfully . How to use it skillfully ? Why does it exist call and apply? stay javascript OOP in , We often define it like this : function ...

  3. JS Medium call、apply、bind Method

    JS Medium call.apply.bind Method One .call() and apply() Method 1. Method definition call Method : grammar :call([thisObj[,arg1[, arg2[,   [,.argN]]] ...

  4. About js Medium call and apply Use understanding

    About js Medium call and apply Use understanding When learning something new , I've seen it before but I don't understand it , Or the memory is not deep place might as well look back at the book knowledge , It helps to deepen the understanding of . As the saying goes -- Consider the past you shall know the future . I don't say much nonsense , Go straight to the code ...

  5. Quickly understand js Medium call,apply The role of

    Today, I was asked js Medium call,apply Differences and uses of , After some explanation , Think of before in force to see a little partner vivid explanation It's not hard to understand , look down MDN You know the , But not often , Yes , We need to turn the brain circuit around . Or for a long time , ...

  6. Promote the development of happiness 10 strip JS skill

    Fish head sums up something that can improve development efficiency JS skill , These techniques are very practical , I think it's very good , I would like to recommend it to you , So with this article . Generate random UID const genUid = () => {  var length = 20 ...

  7. JS Medium call() and apply() Method ( turn )

    from :http://uule.iteye.com/blog/1158829 JS Medium call() and apply() Method Blog classification : JS   1. Method definition call Method :  grammar :call([thisOb ...

  8. [JS] Topic - hijack this by &quot;apply&quot; and &quot;call&quot;

    Ref:  Detailed explanation js Medium apply And call Usage of call and apply The two have exactly the same effect , It's just a different way of accepting parameters . Parameter form : Function.apply(obj,args) call Methods and ...

  9. Take this wave JS skill , Less overtime from now on

    All kinds of business development are inseparable from the processing of data , However, a lot of data encountered are not easy to process . At this time, we need to seek help from search engines . This method is very inefficient , And according to the author's personality, there is no guarantee of his taste . So this text contains a JS ...

Random recommendation

  1. Intro to CSS 3D transforms

    Original address :Intro to CSS 3D transforms, This article is just a part of the translation , The browser compatibility section is omitted ( Outdated ) Perspective The element needs to be set, needs to be set perspec ...

  2. sprite Common operations

    , Anchor point Anchor is all the rotation , Move , Zoom reference point .cocos2-x The default anchor point in is the center point . The anchor point is expressed in scale and the range is 0-,(,) The dot represents the lower left dot ,(,) It stands for the top right . The set function is setAnchorPoint(ccp( ...

  3. Pylint

    [Pylint] pylint Call command for : pylint [options] module_or_package Use Pylint For a module module.py Code check : 1. Enter this module ...

  4. EMA Calculated C# Realization (c# Exponential Moving Average (EMA) indicator )

    It turns out that there is a source code abroad (TechnicalAnalysisEngine src 1.25) Inside to EMA The calculation of : var copyInputValues = input.ToList(); for (int ...

  5. Java Study ----main Detailed explanation

    public class Test1 { public static void main(String[] args) { System.out.println("Hello"); ...

  6. 【 Clock recursively 2】 Find the number... Of two ordered arrays K decimal

    [ subject ] Given two ordered arrays arr1 and arr2, We know that the lengths of the two arrays are m1 and m2, Find the second of two arrays K decimal . Time complexity required O(log(m1 + m2)). [ give an example ] for example arr1 = [1, ...

  7. Django Templates

    Django Template system Official documents Common grammar Just remember two special symbols : {{  }} and  {% %} Variable related uses {{}}, The use of logic {%%}. Variable { Variable name }} The variable name consists of alphanumeric characters and underscores . spot ...

  8. CentOS How to manually add Delete swap District

    SWAP yes Linux Virtual memory in , Used to expand the physical memory is insufficient and used to store temporary data exist . It is similar to Windows Virtual memory in . stay Windows in , You can only use files as virtual memory . and linux You can use files or partitions as ...

  9. win8 How to cancel the automatic shutdown of the system computer

    In the use of win8 Users of the system will encounter the situation that the computer will shut down automatically , This is a win8 It has its own automatic shutdown function , If you want to cancel this function , Just by executing a command . Let's talk about the specific steps . 1. Composite key :win+R, And then in ...

  10. SMS text pdu Pattern parsing

    From the Internet It's a long time In case of infringement Please contact to delete text Mode mainly sends character sets ( Limited ), Can't be used to send Chinese , however hex moder You can send all the characters . pdu moder Supported by all mobile phones , It is mainly divided into 7bit 8b ...