1
類Vehicle
稿黄,具有seats
屬性和drive
方法
class Vehicle{
constructor(seats){ this.seats=seats;}
driver(){
console.log("i am driving");
}
}
kk = new Vehicle('ii');
console.log(kk.seats);
kk.driver();
或者:
class Vehicle{
constructor(seats,driver){
this.seats=seats;
this.driver = driver;
}
}
kk = new Vehicle('ii',function() {
console.log("iuiuiui");})
console.log(kk.seats);
kk.driver();
答案
ii
i am driving
其中第一種實(shí)現(xiàn)方法可以實(shí)現(xiàn)在類中定義方法,對(duì)象直接調(diào)用即可實(shí)現(xiàn)功能族购;第二種方法可以實(shí)現(xiàn)對(duì)象可以自己定義方法里面要實(shí)現(xiàn)的功能
2
類Bus
繼承Vehicle
陵珍,擴(kuò)展了stops
屬性和charge
方法`
class Bus extends Vehicle {
constructor(stop) {
super();
this.stop = stop;
}
charge() {
console.log("i will receive you really high")
}
}
3.
把上述類的寫法?用構(gòu)造函數(shù)的寫法再實(shí)現(xiàn)一次
重寫問(wèn)題1的代碼如下:
function Vehicle(seats) {
this.seats = seats;
this.driver = function (way) {
console.log(way);
}
}
vihi = new Vehicle(9);
console.log(vihi.seats)
vihi.driver("riding");
重寫問(wèn)題2的代碼如下:
function Bus(stops){
this.stops = stops;
this.charge = function(money){
console.log("give me"+ ' '+money);
}
}
Bus.prototype = {
drive : function (way) {
console.log(way);
},
seats:"oo"
}
bus = new Bus("right now");
console.log(bus.stops);
bus.charge("50$");
console.log(bus.seats);
bus.drive("riding");
答案為:
right now
give me 50$
oo
riding