javaScript里面每一个方法都是一个原型对象(prototype),该对象都是可扩展的,千言万语不如一行代码;
例:
// 所需要的参数
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);