var car = {
"wheels":4,
"engines":1,
"seats":5
};
var motorBike = {
"wheels":3,
"engines":1,
"seats":2,
// Only change code below this line.
};
2-Construct JavaScript Objects with Functions
構造函數通常第一個字大寫,用來區分一般函數
this 指向創建出來的對象
var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 5;
};
// Only change code below this line.
var MotorBike = function() {
this.engines=1;
this.wheels=2;
this.seats=2;
};
3-Make Instances of Objects with a Constructor Function
用 new function() 來創建一個實力 instance
var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 5;
};
// Only change code below this line.
var myCar = new Car();
myCar.nickname = "Chacha";
4-Make Unique Objects by Passing Parameters to our Constructor
var Car = function(wheels, seats, engines) {
//Change this constructor
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
//Try it out here
var myCar = new Car(2, 2, 1) ;
5-Make Object Properties Private
建構函數內,自己的函數稱為方法,自己的特徵稱作屬性(忘了)
讓私有資料只能透過方法存取
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
var Bike = function() {
// Only change code below this line.
var gear = 2;
this.getGear = function(){
return gear;
};
this.setGear = function(change){
gear = change;
return gear;
};
};
var myCar = new Car();
var myBike = new Bike();
myBike.getGear(3);