JS关于原型

一、实例

1. new Person()在前

1
2
3
4
5
6
7
8
9
Person.prototype.name = 'sunny';

function Person() {}

var person = new Person();

Person.prototype.name = 'cherry';

console.log(person.name); //cherry

2. new Person()在后

1
2
3
4
5
6
7
8
9
Person.prototype.name = 'sunny';

function Person() {}

Person.prototype.name = 'cherry';

var person = new Person();

console.log(person.name); //cherry

3. 改变写法

1
2
3
4
5
6
7
8
9
10
11
12
13
Person.prototype.name = 'sunny';

function Person() {
//var this = {__proto__ : Person.prototype}
}

var person = new Person();

Person.prototype = {
name : 'cherry'
}

console.log(person.name); //sunny
1
2
3
4
5
6
7
8
这样理解
var obj = {name : "a"};
var obj1 = obj;
obj = {name : "b"};

Person.prototype = {name : "a"};
__proto__ = Person.prototype;
Person.prototype = {name : "b"};

4. new Person最后执行

1
2
3
4
5
6
7
8
9
10
11
12
13
Person.prototype.name = 'sunny';

function Person() {
// var this = {__proto__ : Person.prototype}
}

Person.prototype = {
name : 'cherry'
}

var person = new Person();

console.log(person.name); //cherry

二、隐式添加

1
2
3
4
5
6
7
8
9
Person.prototype.name = 'abc';
function Person() {
// let this = Object.create(Person.prototype);
// let this = {
// __proto__ : Person.prototype
// }
}

let person = new Person();

三、继承

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
// 继承  

//1.圣杯模式
function inherit(Target, Origin) {
function F() {}
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}

// 2.雅虎写法 闭包
var inherit = (function () {
var F = function () {}
return function (Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}());

Father.prototype.lastName = "G";

function Father() {}
function Son() {}

inherit(Son, Father);

var son = new Son();
var father = new Father();