js建構函式
阿新 • • 發佈:2021-01-14
一般變數放建構函式裡, 常量放prototype中
function Car(opt) { this.brand = opt.brand this.color = opt.color this.displacement=opt.displacement } Car.prototype = { price: '50000', yougai:'上汽提供', brand :'北京' } function Per(opt) { this.name = opt.name this.age =opt.age this.income = opt.imcome this.selectCar = function () { var car = new Car(opt.carOpt) console.log(this.name + '挑選了排量:' + car.displacement, '顏色:' + car.color, '品牌:' + car.brand, '價錢:' + car.price, '油蓋供應商:' + car.yougai+'的車') } } var person = { name: '約翰', age: '14', income: '10000', carOpt: { brand:'現代', color:'red', displacement:'122' } } var per = new Per(person) per.selectCar()
結果:約翰挑選了排量:122 顏色:red 品牌:現代 價錢:50000 油蓋供應商:上汽提供的車
注:1.原型prototype是function物件的一個屬性,是個物件
2.prototype是定義建構函式構造出來的每個物件公共祖先,所有被建構函式構造出的物件都可以繼承原型上的屬性和方法
3建構函式中有屬性或方法,就不去呼叫prototype原型上的屬性和方法