0%

原型,原型链和原型链继承

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 所需要的参数
var lenoveObj = {
"name":'联想 Y100',
"address":"上海"
}

var dimension = "100`";

var huaweiObj = {
"name":'huawei P10',
"address":"上海"
}

var powerObj = {
"capacity":'10000mah',
"runtime":'5day'
}

var runsizeObj = {
"name":"lenove",
"runsize":"512M"
}

// 构造函数
var Commodity = function(obj ){
this.address = obj.address;
this.name = obj.name;
this.origin = function( address ){
console.log( "address", this.address )
}
}

//扩展的方法 price()
Commodity.prototype.price = function(price){
console.log("price函数", price )
}

// 需要继承构造函数的方法
var Computer = function(){}

Computer.prototype = new Commodity(lenoveObj);

Computer.prototype.__prototype__ = Commodity.prototype;

// 扩展的方法 runFn()
Computer.prototype.runFn = function(runsize){
console.log( "runsize.runsize:"+runsize.runsize )
console.log( "this.pcWidth:"+this.pcWidth )
}
// 扩展的属性 pcWidth
Computer.prototype.pcWidth = dimension;

// 需要继承构造函数的方法
var Phone = function(){}

// 原型继承 并传入构造函数必要的参数
Phone.prototype = new Commodity(huaweiObj);

// 原型链继承
Phone.prototype.__prototype__ = Commodity.prototype;

// 继承之后扩展的方法 powerFn()
Phone.prototype.powerFn = function(){
console.log("this.address",this.address)
}

//扩展的属性 pingsize
Phone.prototype.pingsize="5`";

// Phone
var huawei = new Phone();
//查看扩展属性
console.log("huawei.name:",huawei.name);
//查看自带方法
huawei.origin();
//查看构造函数的扩展方法
huawei.price("5000")
//检测方法继承来源
console.log(huawei instanceof Commodity ) //判断 instanceof 该方法是否继承于某个构造函数
//查看继承后扩展的方法
huawei.powerFn();


// Computer
var lenove = new Computer();
//查看继承自Computer构造函数下的runFn方法 传参runsizeObj
lenove.runFn(runsizeObj);
------ 本文结束------