方法
1 var people = { 2 name : "zhangsan", 3 birth: 2001, 4 // 方法 5 age : function () { 6 let now = new Date().getFullYear(); 7 return now-this.birth; 8 9 } 10 11 }
调用的时候方法一定要带()
people.age();
如果拆开写,内部写一个函数名字就行
1 function getAge() { 2 let now = new Date().getFullYear(); 3 return now-this.birth; 4 5 } 6 var people1 = { 7 name:"zhangsan", 8 birth: 2002, 9 age:getAge 10 }
此时如果直接调用getAge() NaN 因为此时对象为window
apply函数:在js中可以控制this指向
1 getAge.apply(people,[]); 2 >20 3 people.age(); 4 >20
posted on 2021-05-06 20:03 Love&Share 阅读(43) 评论(0) 编辑 收藏 举报