原型链思考

  • 每个函数原型的构造器是它本身。
  • 每个函数的_proto_属性指向它的构造函数的prototype。

原型链继承+深浅拷贝+值类型/引用类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function Foo(){
this.names = ["Foo"]; // 引用类型
this.hello = 'hello'; // 值类型
}
function foo(){}

foo.prototype = new Foo();

var i1 = new foo();
i1.names.push("i1");
i1.hello = 'world';
console.log(i1.names); // ['Foo', 'i1']
console.log(i1.hello); // 'world'

var i2 = new foo();
console.log(i2.names); // ['Foo', 'i1']
console.log(i2.hello); // 'hello'

var i3 = new Foo();
console.log(i2.names); // ['Foo']
console.log(i2.hello); // 'hello'

原型链示例代码

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
var Foo = new Function();
var foo = new Foo();
Foo.__proto__.constructor === Foo
false

Foo.__proto__ === Function.prototype
true

Function.prototype.__proto__ == Object.prototype
true

Object.prototype.__proto__ == null
true

Foo.prototype.constructor == Foo
true

foo.__proto__ == Foo.prototype
true

foo.constructor == Foo
true

var Bar = new Object();
Bar.__proto__ == Object.prototype
true
Bar.constructor == Object
true

instanceof

1
2
instanceof原理就是一层一层查找 __proto__,如果和 constructor.prototype 相等则返回 true,
如果一直没有查找成功则返回 false。
-------------本文结束感谢您的阅读-------------
坚持原创,感谢支持!