1+ <!DOCTYPE html>
2+ < html >
3+ < head >
4+ < meta charset ="utf-8 ">
5+ < meta http-equiv ="X-UA-Compatible " content ="IE=edge,chrome=1 ">
6+ < title > Examples</ title >
7+ < meta name ="description " content ="">
8+ < meta name ="keywords " content ="">
9+ < link href ="" rel ="stylesheet ">
10+ </ head >
11+ < body >
12+ < script >
13+ // 在一个对象里绑定的函数,称为对象的方法
14+ var xiaoming = {
15+ alert : function ( ) {
16+ console . log ( 'alert重写' ) ;
17+ console . info ( this ) ;
18+ }
19+ }
20+
21+
22+ var oldAlert = window . alert ;
23+ window . alert = xiaoming . alert ;
24+ alert ( ) ; // alert重写 // window{}
25+ xiaoming . alert ( ) ; // alert重写 Object{}
26+ alert ( 3 ) ; // alert重写 // window{}
27+ alert = oldAlert ;
28+ alert ( 3 ) ; // 3
29+
30+ // javascript 全局作用域只有一个
31+
32+ function getSex ( ) {
33+ console . log ( this . sex1 ) ;
34+ }
35+
36+ var chenyi = {
37+ name : 'chenyi' ,
38+ birth : 2014 ,
39+ sex1 : 'boy' ,
40+ sex : getSex ,
41+ age : function ( ) {
42+ var y = new Date ( ) . getFullYear ( ) ;
43+ console . info ( y ) ; // 2017
44+ return y - this . birth ; // this => chenyi
45+ } ,
46+ height : function ( ) {
47+ var _this = this ;
48+ function getHeight ( ) {
49+ return _this . birth + 90 ;
50+ }
51+ return getHeight ( ) ;
52+ }
53+ }
54+ console . log ( chenyi . age ( ) ) ; // 3
55+ // age(); // age is not defined
56+
57+ console . log ( chenyi . height ( ) ) ; // NaN ==> 2104
58+
59+ chenyi . sex ( ) ; // boy
60+ getSex . apply ( chenyi , [ ] ) ; // boy
61+
62+ console . log ( Math . max . apply ( null , [ 7 , 1 ] ) ) ; // 7
63+ console . log ( Math . max . call ( null , 5 , 9 ) ) ; // 9
64+
65+ // 调用普通函数时用null 绑定 this
66+
67+
68+ var oldParseInt = parseInt ;
69+ var count = 0 ;
70+ window . parseInt = function ( ) {
71+ count ++ ;
72+ oldParseInt . apply ( null , arguments ) ;
73+ }
74+ parseInt ( 4 ) ;
75+ parseInt ( 4 ) ;
76+ parseInt ( 4 ) ;
77+ console . log ( count ) ; // 3
78+ </ script >
79+ </ body >
80+ </ html >
0 commit comments