This in JavaScript (you don't know JavaScript)

Source: Internet
Author: User

This in JavaScript, when it comes to JavaScript, is all about how dexterous and important it is, but doesn't care about it, and it's really important when you get to know the JavaScript step-by-step. So, I spent about 2 weeks to check and read the books before, the full picture of this is shown below. One, this is what--based on the context of the call location; different call locations, this value is different. everyone is in JavaScript. This has two misconceptions:
(1) This points to the function itself
(2) This refers to the scope of a function

The scope cannot be accessed through JavaScript code, which exists inside the JavaScript engine. Whenever you mix this with the lookup of a lexical scope, be sure to remind yourself that this is not possible.

This is binding at run time, not binding at compile time, and its context depends on the various conditions of the function call. The binding of this is not related to the location of the function declaration, only depending on where the function is called (that is, how the function is called). Example:

var foo = "Golbal foo";
var myobj = {foo: ' myobj foo '};
var say = function () {
	console.log (this.foo);
}

Myobj.say = say;
Myobj.say ();	Results: myobj foo
say ();		Result: Golbal foo
second, why use this
var me = {
	name: "Fenfei"
};

Do not use this to invoke
function speak (name) {
	Console.log ("Hello, I ' m" + name);
}
Speak (Me.Name);		Hello, i ' m Fenfei

//Use this, invoke
function speak () {
	console.log ("Hello, I ' m" + this.name);
}
Speak.call (me);		Hello, I ' m Fenfei

This provides a more elegant way to implicitly "pass" object references, so the APIs can be designed to be more concise and easy to reuse. three. This is the four binding rules 1. Default binding--function call Type: Standalone function call, this points to the global object.

var a = "foo";
function foo () {
	console.log (THIS.A);
}
Foo ();	"Foo"

In strict mode, the global object will not be able to use the default binding, so this is bound to undefined.

var a = "foo";
function foo () {
	"use strict";
	Console.log (THIS.A);
}
Foo ();	Typeerror:this is undefined
2. Implicit binding-whether the call location has a context object, or is owned or contained by an object
function foo () {
	console.log (THIS.A);
}
var obj1 = {
	a:2,
	foo:foo
}
var obj2 = {
	a:1,
	obj1:obj1
}
Obj2.obj1.foo ();	Results: 2

When Foo () is called, its foothold points to the Obj1 object, and the implicit binding rule binds this to the context object in the function call.
The object attribute reference chain has only the topmost layer, or the last layer affects the call location. Note: Implicit loss of

The common this binding problem is that an "implicitly bound" function loses a bound object, or "default binding," which binds this to the global object (in strict mode, undefined).

var a = "foo";
function foo () {
	console.log (THIS.A);
}
var obj = {
	a:2,
	foo:foo
}
var bar = Obj.foo;
Bar ();	"Foo"

Although bar is a reference to Obj.foo, it actually refers to the Foo function itself, so the bar () is actually called without any modification, so the default binding is applied.

var a = "foo";
function foo () {
	console.log (THIS.A);
}
function Dofoo (FN) {		//var fn = Obj.foo
	fn ();
}
var obj = {
	a:2,
	foo:foo
}
Dofoo (Obj.foo);	"Foo"

settimeout (Obj.foo, MB);	"Foo"

Parameter passing is actually an implicit assignment, so the passed-in function is implicitly assigned (LHS) 3. Display bindings (1) Call, apply
(2) Hard binding

function foo () {
	console.log (THIS.A);
}
var obj = {	a:2};
var bar = function () {
	foo.call (obj);
};
Bar (); 2
settimeout (bar, 1000);	2
bar.call (window);	2

The function bar () was created, and Foo.call (obj) was manually called internally, forcing the this binding of Foo to obj. Regardless of how the function bar is called later, it is always manually raised in obj with Foo. The forced binding of this display is called "hard binding." 4. The new bind new Call function automatically performs the following actions:
(1) Create (or construct) an entirely new object;
(2) The new object will be connected with [[prototype]];
(3) This new object is bound to this of the function call;
(4) If the function does not return other objects, the function call in the new expression will automatically return the object.
Iv. Priority Level

Knowing the four rules of this binding in a function call, all you need to do is find the call location of the function and determine which rule to match. 1. Whether the function is new binding. If it is, this binds the newly created object.

var bar = new Foo ();
2. Whether the function displays bindings or hard bindings through call or apply. If it is, this binds the specified object.
var bar = Foo.call (obj);
3. Whether the function is implicitly invoked in a context object. If it is, this binds the context object.
var bar = Obj.foo ();
4. None of the above, use default bindings. If you are bound to undefined in strict mode, you are bound to the global Window object.
var bar = foo ();
Five, binding this note point 1. Ignore this

The binding object, null or undefined, is passed in call, apply, and bind, and the invocation is ignored, and the default binding rule is actually applied.

function foo () {
	console.log (THIS.A);
}
var a = 1;
Foo.call (null, 2);			1
foo.apply (Undefined, [3]);	1
2. Indirect reference
function foo () {
	console.log (THIS.A);
}
var a = 2;
var o = {A:3,foo:foo};
var p = {A:4};
O.foo ();			3
(P.foo = O.foo) ();	2 Indirect reference
var pfoo = O.foo;
Pfoo ();			2 implicit loss
Note: The same as the "implicit loss" result above, but the process is not the same, distinguish between ...
3. ES6 Arrow Function

The arrow function does not use the four standard rules of this, but rather determines this by the outer (function or global) scope.
The binding of the arrow function cannot be modified. Often used in callback functions, such as event handlers or timers. This is the same as the This = self mechanism in the code before ES6.

function foo () {
	settimeout (() =>{
		console.log (THIS.A);
	},100);
var obj = {A:2};
Foo.call (obj);
Equivalent to:
function foo () {
	var self = this;
	settimeout (function () {
		console.log (SELF.A);
	},100);
}
var obj = {A:2};
Foo.call (obj);
vi. How to determine this 1. (Implicit binding) if a member of an object is a function, this point points to the current object when this method is called from this object.
var Fenfei = {
	firstname: "Li",
	LastName: "Gang",
	timetravel:function (year) {
		Console.log ( This.firstname + "" + This.lastname + "is time traveling to" + year);
	}

Fenfei.timetravel (2014);	Li Gang is time traveling to 2014 (Parent/Owner object: Fenfei)
2. (Privacy bindings) You can refer to the Timetravel method on the Fenfei object by creating a new object.
var camile = {
	firstname: "Li",
	LastName: "Yunxia"
}

camile.timetravel = Fenfei.timetravel;
Camile.timetravel (2014);	Li Yunxia is time traveling to 2014 (Parent/Owner object: Camile)
Note: This example distinguishes the above "implicit loss", "indirect reference" ...
3. (implicitly lost) use a variable to save a reference to the Fenfei.timetravel method
var gettimetravel = fenfei.timetravel;
Gettimetravel (2014);	Undefined undefined is time traveling to 2014 (Parent/Owner object: Window;window object does not have FirstName and LastName attributes)

PS: Remember this in the method will point to the parent/owner object that called it. Whenever a function is invoked, we must look at the square brackets or the adjacent position to the left of the parentheses, and if we see a reference (Reference), then the this value passed to the function is the object to which the method belongs, and if not, So it's pointing to the global object. 4. This is inside of the method called asynchronously

<button id= "Async" > Click me </button>
var btndom = document.getElementById ("async");
Btndom.addeventlistener (' click ', fenfei.timetravel);//undefined undefined is time traveling to [object MouseEvent] (Parent/ Owner object: Button)

btndom.addeventlistener (' click ', Function (e) {
	fenfei.timetravel (2014);//li gang is Time Traveling to 2014 (Parent/Owner object: Fenfei)
});
5. (new binding) This in the constructorWhen you use a constructor to create an instance of an object, this in the constructor is the new instance.
var timetravel = function (FName, lName) {
	this.firstname = fName;
	This.lastname = LName;
}

var Fenfei = new Timetravel ("Li", "Gang");
Console.log (Fenfei.firstname + "" + fenfei.lastname);		Li Gang
6. (show bindings) call and apply method set this value
var camile = {
	firstname: "Li",
	LastName: "Yunxia"
}

FenFei.timeTravel.call (camile,2014);		Li Yunxia is time traveling to 2014 (specifying this object is Camile)
FenFei.timeTravel.apply (camile,[2014));	Li Yunxia is time traveling to 2014 (Specify this object to be Camile)
PS: Pay attention to compare with the above "2" place
7. (Show bindings) bind bind a function to an object (ES5)
function f (Y) {return
	this.x + y;
}
var o = {x:1};
/* F.bind (O) Returns a new function, and calling G (2) invokes the original function f () as an O method to invoke
/var g = F.bind (o);	
g (2);	3

add: Before ES5 method simulates bind () method

function Mybind (f, O) {
	if (f.bind) {return
		f.bind (o);
	} else{return
		function () {return
			f.apply (o, arguments);
		}
}}

Bind's role and apply,call are similar to changing the execute context of a function, which is the point of the This keyword when runtime. But the use method is slightly different. A function can be executed later after bind.   Seven, supplemental 1. When you use new to create multiple instances of a function, these instances share prototype. when a property is added directly to this in an instance, a property with the same name in the prototype is hidden.
If you want to access the property value in prototype instead of your own Set property value:
(1) Delete the property that the instance added itself: delete Instance name. Property name
(2) Direct access to properties in prototype: Thing.prototype.name

function Thing () {}
Thing.prototype.name = "Leegang";
Thing.prototype.getName = function () {
	console.log (this.name);
}
Thing.prototype.setName = function (newName) {
	this.name = newName;
}
Thing.prototype.deleteName = function () {
	delete this.name;
}

var thing = new Thing ();	/*thing:thing {}*/
thing.setname ("Liyunxia");	/*thing:thing {name: "Liyunxia"}*/
thing.getname ();		Results: Liyunxia
thing.deletename ();		/*thing:thing {}*/
thing.getname ();		Result: Leegang	thing.__proto__ is thing {name: "Leegang"}

thing.name = "Liyunxia";	/*thing {name: "Liyunxia"}*/
thing.getname ();		Results: Liyunxia
Delete thing.name;		/*thing:thing {}*/
thing.getname ();		Result: Leegang thing.__proto__ is thing {name: "Leegang"}
2. CorrieTransforms a function that accepts multiple parameters into a function that accepts a single argument (the first parameter of the original function), and returns a new function that accepts the remaining arguments and returns the result if the other arguments are necessary.
var sum = function (x, y) {return
	x + y;
}
var succ = Sum.bind (null, 1);
SUCC (2);	3

function f (y, z) {return
	this.x + y +z;
}
var g = F.bind ({x:1}, 2);
g (3);	6
Reprint please specify the Source: http://blog.csdn.net/ligang2585116

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.