The difference between JS arrow function and ordinary function 1. Bubondin this
Each newly defined function has its own this value before the arrow function appears
var myObject = {value:1, getvalue:function ( {console.log (this.value)}, Double:function (return function ( console.log (this.value = Span class= "Hljs-keyword" >this.value * 2); }}}myobject.double () (); //wants value multiplied by 2myobject.getvalue (); //1
The
Assigns this to a variable in ECMAscript5 to resolve:
var myObject = {value:1, getvalue:function ( {console.log (this.value)}, Double:function (var that = this; return function (console.log (that.value = that.value * 2);}} Myobject.double () (); //2myobject.getvalue (); //2
In addition, you can also use the BIND function to pass the expected this value to the double () function.
var myObject = {value:1, getvalue: function ( Console.log (this.value)}, double: function ( return function (console.log (this.value = this.value * 2); }.bind (this)}}myobject.double () (); //2myobject.getvalue (); //2
The
Arrow function captures the this value of its context as its own this value, so the following code will run as expected.
var myObject = { value:1, getValue:function(){ console.log(this.value) }, double:function(){ //回调里面的 `this` 变量就指向了期望的那个对象了 return ()=>{ console.log(this.value = this.value * 2); } }}myObject.double()(); myObject.getValue();
2. Using call () and apply ()
Since this is already binding at the lexical level, invoking a function via the call () or the Apply () method simply passes in the parameter, and has no effect on this:
var myObject = {Value1,AddfunctionA) {var f = (v) = + V + this.value; return f (a);}, addthrucall:function (a) {var f = (v) = v + this.value; var B = {value:2}; return F.call (B,a); }}console.log (Myobject.add (1)); //2console.log (Myobject.addthrucall ( 1)); //2
3. The arrow function does not bind arguments, instead of using rest parameters ... Solve
var foo = (...args) => { return args[0]}console.log(foo(1)) //1
4. Using the new operator
The arrow function cannot be used as a constructor, and with new it throws an error.
var Foo = () => {};var foo = new Foo(); //Foo is not a constructor
5. Using the prototype attribute
The arrow function does not have a prototype property.
var foo = () => {};console.log(foo.prototype) //undefined
6. Cannot simply return object literals
var func = () => { foo: 1 };// Calling func() returns undefined!var func = () => { foo: function() {} };// SyntaxError: function statement requires a name//如果要返回对象字面量,用括号包裹字面量var func = () => ({ foo: 1 });
7. Arrow function does not define this binding when the method is used
var obj = { value:1, add:() => console.log(this.value), double:function(){ console.log(this.value * 2) }}obj.add(); //undefinedobj.double(); //2
8. Arrow function cannot wrap
var func = () => 1; // SyntaxError: expected expression, got ‘=>‘
The difference between an arrow function and a normal function