Method
A method that binds a function in an object called this object
var xiaoming Span class= "OP" >= { name : ' xiaoming ' brith : Span class= "DV" >1997 age : function () { var y =
new
date (). getfullyear () return y - this . brith } } xiaoming . age () //
When we want to replace the lengthy with a third-party variable xiaoming.age() , let's look at the effect
// 写法1=xiaoming.age;fn() // NaN// 写法2=xiaoming.age();// 21
When we use the first form of writing, the Age method is actually proposed, then the this object pointed to becomes window , so thatNaN
So in order to avoid being called externally, and you can recycle it, age() we introducethat
' use strict 'varXiaoming= { Brith: 1997, Age: function(){ //Get this from the beginning of the methodThat= This; function Getagefrombrith(){ varY= New Date.getFullYear(); returnY-That; } return Getagefrombrith(); }}xiaoming. Age(); //varFn= xiaoming. Age;fn(); //uncaught Typeerror:cannot Read Property ' birth ' of undefined
Apply and call
We know that a function this is meant to refer to an object, so what if we want to refer to what an object should do?
This can be used apply with cell the
functiongetAge{returnthis.age;}var={ name:‘kaso‘, age:20}getAge.apply(xiaoming, []);//20getAge.call(xiaoming, []); //20
Appay | Call Difference
//调用Math.max(3, 4, 5)Math.max.apply(null, [3,4,5// 5Math.max.call(null,3,4,5) // 5
Decorative Device
Adorners are used to rename functions, such as the transformation of the alert window and console with the dual function
// 保存原来的 alertvar= alert;window.alert=function{ alert(this); console.log(this); returnoldAlert.apply(null, arguments);}alert("halo")
function methods that and apply