JavaScript继承详解(二)

释放双眼,带上耳机,听听看~!

 

 

这一章我们将会重点介绍JavaScript中几个重要的属性(this、constructor、prototype), 这些属性对于我们理解如何实现JavaScript中的类和继承起着至关重要的作用。

this

this表示当前对象,如果在全局作用范围内使用this,则指代当前页面对象window; 如果在函数中使用this,则this指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用apply和call两个全局方法来改变函数中this的具体指向。

先看一个在全局作用范围内使用this的例子:


1
2
3
4
5
6
7
8
9
10
11
12
1        <script type="text/javascript">  
2
3            console.log(this === window);  // true  
4
5            console.log(window.alert === this.alert);  // true  
6
7            console.log(this.parseInt("021", 10));  // 10  
8
9        </script>  
10
11        
12

 

函数中的this是在运行时决定的,而不是函数定义时,如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
1        // 定义一个全局函数  
2
3        function foo() {  
4
5            console.log(this.fruit);  
6
7        }  
8
9        // 定义一个全局变量,等价于window.fruit = "apple";  
10
11        var fruit = "apple";  
12
13        // 此时函数foo中this指向window对象  
14
15        // 这种调用方式和window.foo();是完全等价的  
16
17        foo();  // "apple"  
18
19
20        // 自定义一个对象,并将此对象的属性foo指向全局函数foo  
21
22        var pack = {  
23
24            fruit: "orange",  
25
26            foo: foo  
27
28        };  
29
30        // 此时函数foo中this指向window.pack对象  
31
32        pack.foo(); // "orange"  
33
34        
35

 

全局函数apply和call可以用来改变函数中this的指向,如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1        // 定义一个全局函数  
2
3        function foo() {  
4
5            console.log(this.fruit);  
6
7        }  
8
9        
10        // 定义一个全局变量  
11
12        var fruit = "apple";  
13
14        // 自定义一个对象  
15
16        var pack = {  
17
18            fruit: "orange"  
19
20        };  
21
22        
23        // 等价于window.foo();  
24
25        foo.apply(window);  // "apple"  
26
27        // 此时foo中的this === pack  
28
29        foo.apply(pack);    // "orange"  
30
31        
32

注:apply和call两个函数的作用相同,唯一的区别是两个函数的参数定义不同。

 

因为在JavaScript中函数也是对象,所以我们可以看到如下有趣的例子:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
1        // 定义一个全局函数  
2
3        function foo() {  
4
5            if (this === window) {  
6
7                console.log("this is window.");  
8
9            }  
10
11        }  
12
13        
14        // 函数foo也是对象,所以可以定义foo的属性boo为一个函数  
15
16        foo.boo = function() {  
17
18            if (this === foo) {  
19
20                console.log("this is foo.");  
21
22            } else if (this === window) {  
23
24                console.log("this is window.");  
25
26            }  
27
28        };  
29
30        // 等价于window.foo();  
31
32        foo();  // this is window.  
33
34        
35        // 可以看到函数中this的指向调用函数的对象  
36
37        foo.boo();  // this is foo.  
38
39        
40        // 使用apply改变函数中this的指向  
41
42        foo.boo.apply(window);  // this is window.  
43
44        
45

 

prototype

我们已经在第一章中使用prototype模拟类和继承的实现。 prototype本质上还是一个JavaScript对象。 并且每个函数都有一个默认的prototype属性。
如果这个函数被用在创建自定义对象的场景中,我们称这个函数为构造函数。 比如下面一个简单的场景:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1        // 构造函数  
2
3        function Person(name) {  
4
5            this.name = name;  
6
7        }  
8
9        // 定义Person的原型,原型中的属性可以被自定义对象引用  
10
11        Person.prototype = {  
12
13            getName: function() {  
14
15                return this.name;  
16
17            }  
18
19        }  
20
21        var zhang = new Person("ZhangSan");  
22
23        console.log(zhang.getName());   // "ZhangSan"  
24
25        
26

作为类比,我们考虑下JavaScript中的数据类型 – 字符串(String)、数字(Number)、数组(Array)、对象(Object)、日期(Date)等。 我们有理由相信,在JavaScript内部这些类型都是作为构造函数来实现的,比如:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1        // 定义数组的构造函数,作为JavaScript的一种预定义类型  
2
3        function Array() {  
4
5            // ...  
6
7        }  
8
9        
10        // 初始化数组的实例  
11
12        var arr1 = new Array(1, 56, 34, 12);  
13
14        // 但是,我们更倾向于如下的语法定义:  
15
16        var arr2 = [1, 56, 34, 12];  
17
18        
19

同时对数组操作的很多方法(比如concat、join、push)应该也是在prototype属性中定义的。
实际上,JavaScript所有的固有数据类型都具有只读的prototype属性(这是可以理解的:因为如果修改了这些类型的prototype属性,则哪些预定义的方法就消失了), 但是我们可以向其中添加自己的扩展方法。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
1        // 向JavaScript固有类型Array扩展一个获取最小值的方法  
2
3        Array.prototype.min = function() {  
4
5            var min = this[0];  
6
7            for (var i = 1; i < this.length; i++) {  
8
9                if (this[i] < min) {  
10
11                    min = this[i];  
12
13                }  
14
15            }  
16
17            return min;  
18
19        };  
20
21        
22        // 在任意Array的实例上调用min方法  
23
24        console.log([1, 56, 34, 12].min());  // 1  
25
26        
27

注意:这里有一个陷阱,向Array的原型中添加扩展方法后,当使用for-in循环数组时,这个扩展方法也会被循环出来。
下面的代码说明这一点(假设已经向Array的原型中扩展了min方法):


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1        var arr = [1, 56, 34, 12];  
2
3        var total = 0;  
4
5        for (var i in arr) {  
6
7            total += parseInt(arr[i], 10);  
8
9        }  
10
11        console.log(total);   // NaN  
12
13        
14        
15

解决方法也很简单:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1        var arr = [1, 56, 34, 12];  
2
3        var total = 0;  
4
5        for (var i in arr) {  
6
7            if (arr.hasOwnProperty(i)) {  
8
9                total += parseInt(arr[i], 10);  
10
11            }  
12
13        }  
14
15        console.log(total);   // 103  
16
17        
18

 

constructor

constructor始终指向创建当前对象的构造函数。比如下面例子:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1        // 等价于 var foo = new Array(1, 56, 34, 12);  
2
3        var arr = [1, 56, 34, 12];  
4
5        console.log(arr.constructor === Array); // true  
6
7        // 等价于 var foo = new Function();  
8
9        var Foo = function() { };  
10
11        console.log(Foo.constructor === Function); // true  
12
13        // 由构造函数实例化一个obj对象  
14
15        var obj = new Foo();  
16
17        console.log(obj.constructor === Foo); // true  
18
19        
20        // 将上面两段代码合起来,就得到下面的结论  
21
22        console.log(obj.constructor.constructor === Function); // true  
23
24        
25

 

但是当constructor遇到prototype时,有趣的事情就发生了。
我们知道每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数。如下例所示:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1        function Person(name) {  
2
3            this.name = name;  
4
5        };  
6
7        Person.prototype.getName = function() {  
8
9            return this.name;  
10
11        };  
12
13        var p = new Person("ZhangSan");  
14
15        
16        console.log(p.constructor === Person);  // true  
17
18        console.log(Person.prototype.constructor === Person); // true  
19
20        // 将上两行代码合并就得到如下结果  
21
22        console.log(p.constructor.prototype.constructor === Person); // true  
23
24        
25

当时当我们重新定义函数的prototype时(注意:和上例的区别,这里不是修改而是覆盖), constructor的行为就有点奇怪了,如下示例:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1        function Person(name) {  
2
3            this.name = name;  
4
5        };  
6
7        Person.prototype = {  
8
9            getName: function() {  
10
11                return this.name;  
12
13            }  
14
15        };  
16
17        var p = new Person("ZhangSan");  
18
19        console.log(p.constructor === Person);  // false  
20
21        console.log(Person.prototype.constructor === Person); // false  
22
23        console.log(p.constructor.prototype.constructor === Person); // false  
24
25        
26

为什么呢?
原来是因为覆盖Person.prototype时,等价于进行如下代码操作:


1
2
3
4
5
6
7
8
9
10
11
12
1        Person.prototype = new Object({  
2
3            getName: function() {  
4
5                return this.name;  
6
7            }  
8
9        });  
10
11        
12

而constructor始终指向创建自身的构造函数,所以此时Person.prototype.constructor === Object,即是:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1        function Person(name) {  
2
3            this.name = name;  
4
5        };  
6
7        Person.prototype = {  
8
9            getName: function() {  
10
11                return this.name;  
12
13            }  
14
15        };  
16
17        var p = new Person("ZhangSan");  
18
19        console.log(p.constructor === Object);  // true  
20
21        console.log(Person.prototype.constructor === Object); // true  
22
23        console.log(p.constructor.prototype.constructor === Object); // true  
24
25        
26

怎么修正这种问题呢?方法也很简单,重新覆盖Person.prototype.constructor即可:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1        function Person(name) {  
2
3            this.name = name;  
4
5        };  
6
7        Person.prototype = new Object({  
8
9            getName: function() {  
10
11                return this.name;  
12
13            }  
14
15        });  
16
17        Person.prototype.constructor = Person;  
18
19        var p = new Person("ZhangSan");  
20
21        console.log(p.constructor === Person);  // true  
22
23        console.log(Person.prototype.constructor === Person); // true  
24
25        console.log(p.constructor.prototype.constructor === Person); // true  
26
27        
28

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++迭代器

2022-1-11 12:36:11

安全网络

Mina、Netty、Twisted一起学(二):TCP消息边界问题及按行分割消息

2021-8-18 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索