Javascript原型链的一点理解

在进行这篇文章之前,我先通过typeof关键字来划分一下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
var num = 2;
var str = "";
var bool = true;
var fun = function(){};
var obj = {};
var arr = [];

console.log(typeof num); //number
console.log(typeof str); //string
console.log(typeof bool); //boolean
console.log(typeof fun); //function

console.log(typeof obj); //object
console.log(typeof arr); //object
console.log(typeof null); //object

//所以下面这两个对象不需要new后使用
console.log(typeof JSON); //object
console.log(typeof Math); //object

console.log(typeof Object); //function
console.log(typeof Date); //function
console.log(typeof String); //function
console.log(typeof Boolean); //function
console.log(typeof RegExp); //function
console.log(typeof Array); //function
console.log(typeof ArrayBuffer); //function
console.log(typeof Function); //function
console.log(typeof Error); //function

那么,根据上面typeof结果:

  • 基础类型:结果为 number,string,boolean的;
  • 对象类型:结果为 object 的;
  • 引用类型:结果为 function 的。
    之所以这样区分,是因为基础类型是没有构造函数的,对象类型的构造函数指向它的原型,但是不需要通过 new 得到一个实例对象,而引用类型的使用是可以先通过 new 一个实例对象的,当然,引用类型也可以直接使用
    那么本文讲的是原型链和面向对象的继承,自然只需要关注引用类型。

原型继承

下面通过一段代码调试,查看javascript是怎么实现原型链的继承的:

1
2
3
4
5
6
7
8
9
10
11
window.onload = function() {  
var Parent = function(){
this.name = "莱斯利"
this.hellow = function(){
console.log("hellow");
}
};
console.dir(Parent);
var child = new Parent();
console.dir(child);
}

再用typeof查看一下类型:

1
2
console.log(typeof Parent);//function
console.log(typeof child); //object

对比两个输出:
1、这里,Parent就是引用类型,child是Parent的实例化对象,也就是对象类型;
2、Parent输出的是函数原型,带有一个属性prototype,且prototype属性指向Parent函数本身,_proto_指向function();
3、child输出的是Parent实例对象,带有一个属性name,一个方法hellow,_proto_则指向了Parent。

小结:

1、要区分var str = ‘’和var str = new String(‘’),只需要typeof一下就能看出来了,因为一个为基础类型string,一个为实例化对象object,所以他们也不会 === ;
2、javascript的原型继承是通过_proto_属性实现的,实例对象的**__proto\**指向了他的原型;
3、两个对象类型的变量永远不可能相等,这也是为什么 console.log([] == []); //false 了。

另外,还可以通过instanceof查看parent和child的原型:

1
2
console.log(Parent instanceof Function); //true
console.log(child instanceof Parent); //true

小补充,注意不是new一个对象,而是直接调用函数:

1
2
3
4
var x = 1;
console.log(String(x) === (x + "")); //true
console.log(Number(x) === (+x)); //true
console.log(Boolean(x) === (!!x)); //true

关于string的slice和splice:

1
2
3
var x = 'test str';
console.log(typeof x); //string
console.log(x.slice(0, 1)); //t

感谢您的阅读,有不足之处请在评论为我指出!

参考资料

版权声明:本文为博主原创文章,未经博主允许不得转载。本文地址 http://yangyuji.github.io/2015/07/09/javascript-chain/