before we get started, let’s review the way we Create a Class:
开始之前,我们先复习一下Class的建立方式:
function Person(name,age) {
this.name = name;
this.age = age;
}
// Let's make bob again, using our constructor
var bob = new Person("Bob Smith", 30);
比如:
function Dog (breed) {
this.breed = breed;
};
var bark = function(){ //这种就是独立于class之外的,与后面object就无关了。
console.log("Woof");
};
// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
//Dog.prototype.bark = function() {
// console.log("Woof");
//};
//buddy.bark();
// here we make snoopy
var snoopy = new Dog("Beagle");
/// this time it works!
//snoopy.bark();
bark();
其实注入回class的method应该是这样:“className.prototype.methodName = function(){}”
function Dog (breed) {
this.breed = breed;
};
//var bark = function(){
// console.log("Woof");
//};
// here we make buddy and teach him how to bark
var buddy = new Dog("golden Retriever");
//teach Dog how to bark:
Dog.prototype.bark = function() {
console.log("Woof");
};
buddy.bark(); //bark
// here we make snoopy Obj
var snoopy = new Dog("Beagle");
/// this time it works!
snoopy.bark();
//bark();
// create your Animal class here
function Animal(name, numLegs){ //no "="
this.name = name; //notice "this"
this.numLegs = numLegs;
};
// create the sayName method for Animal
Animal.prototype.sayName = function(){
console.log("Hi my name is "+ this.name ); //notice "+"
};
// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();
实质是继承inheritance
inheritance lets us see and use properties and methods from another class. To say that Penguin inherits from Animal, we need to set Penguin’s prototype to be Animal.
// the original Animal class and sayName method
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};
// define a Penguin class
function Penguin(name){
this.name = name;//constructor only take "name"
this.numLegs = 2;//cuz all penguins have 2 legs
}
//define a Emperor class
function Emperor(name){
this.name = name;
}
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();
var myPenguin = new Penguin("Sallivan");
myPenguin.sayName();
console.log(myPenguin["name"] + " has " + myPenguin.numLegs +" legs");
var myEmperor = new Emperor("Bee");
console.log(myEmperor["name"] + " has " + myEmperor.numLegs +" legs");
这是关于Public和Private变量/method的声明,使用,和访问的主题。
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
//ok, let's define a public method
this.getBalance = function(){
return bankBalance;
}
}
var john = new Person('John','Smith',30);
console.log(john.bankBalance);
// create a new variable myBalance that calls getBalance()
var myBalance = john.getBalance();
console.log(myBalance);
在此之前,需要了解一下返回的如果是个method, 那后面要var一个method来装它,再用var的这个method来access that private variable;
e.g:
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
var returnBalance = function() {
return bankBalance;
};
// create the new public function here
this.askTeller = function(){
return returnBalance;//omg! 居然可以这样?
};
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);//here will cause undefined error
var myBalanceMethod = john.askTeller(); //!!!this line is so important!!!!
var myBalance = myBalanceMethod();
console.log(myBalance);
function Person(first, last, age){
this.first = first;
this.last = last;
this.age = age;
var bankBalance = 7500;
this.askTeller = function(password){
if (password == 1234) return bankBalance;
else return "wrong password";
}
}
//create an object john
var john = new Person("John","Smith",28);
var myBalance = john.askTeller(1234);
console.log(myBalance);
every JavaScript object has some baggage associated with it? Part of this baggage was the hasOwnProperty method available to all objects. Now let’s see where this came from…
If we have just a plain object (i.e., not created from a class constructor), recall that it automatically inherits from Object.prototype. Could this be where we get hasOwnProperty from? How can we check?
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType);
// now let's examine it!, "hasOwnProperty" is a method!
var hasOwn = Object.prototype.hasOwnProperty('hasOwnProperty');
console.log(hasOwn);
/*Can I use this onto class Person? function Person(name , age){ this.name = name; this.age = age; } var john = new Person("John", 28); var john_hasOwn = john.name('name'); console.log(john_hasOwn); */
这个场景是收银员cashRegister的object。
注意object内method的声明与使用,完了注意,号分隔。
var cashRegister = {
total:0,
add: function(itemCost){
this.total += itemCost;
},
scan: function(item,quantity) {
switch (item) {
case "eggs": this.add(0.98*quantity); break;
case "milk": this.add(1.23*quantity); break;
case "magazine": this.add(4.99*quantity); break;
case "chocolate": this.add(0.45*quantity); break;
}
},//notice this , (comma) for "scan"
};
// scan each item 4 times
cashRegister.scan("eggs",4);
cashRegister.scan("milk",4);
cashRegister.scan("magazine",4);
cashRegister.scan("chocolate",4);
//Show the total bill
console.log('Your bill is '+cashRegister.total);
function StaffMember(name,discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}
var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);
// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("me",20);
var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction : function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount:function(employee){
this.total -= this.total*employee.discountPercent/100;
},
};
cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount
cashRegister.applyStaffDiscount(me);
// Show the total bill
console.log('Your bill is '+cashRegister.total.toFixed(2));