2012-05-12 09:34:41Morris
[JavaScript] Introduction to Objects II
Privacy Please!
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
}
// create your Person
var john = new Person("A", "B", 5);
// try to print his bankBalance
console.log(john.bankBalance);
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 function here
this.askTeller = function() {
return returnBalance();
};
this.myBalanceMethod = function() {
return askTeller();
}
}
var john = new Person('John','Smith',30);
console.log(john.returnBalance);
var myBalanceMethod = john.askTeller();
var myBalance = myBalanceMethod();
console.log(myBalance);
function Person(first,last,age) {
this.firstname = first;
this.lastname = last;
this.age = age;
var bankBalance = 7500;
this.askTeller = function(pass) {
if (pass == 1234) return bankBalance;
else return "Wrong password.";
};
}
var john = new Person('John','Smith',30);
/* the variable myBalance should access askTeller()
with a password as an argument */
var myBalance = john.askTeller(1234);
Objects in Review Are Closer Than They Appear
var languages = {
english: "Hello!",
french: "Bonjour!",
notALanguage: 4,
spanish: "Hola!"
};
// print hello in the 3 different languages
for(var x in languages) {
if(typeof languages[x] == "string")
console.log(languages[x]);
}
function Dog (breed) {
this.breed = breed;
};
// add the sayHello method to the Dog class
Dog.prototype.sayHello = function() {
console.log("Hello this is a "+this.breed+" dog");
}
// so all dogs now can say hello
var yourDog = new Dog("golden retriever");
yourDog.sayHello();
var myDog = new Dog("dachshund");
myDog.sayHello();
// what is this "Object.prototype" anyway...?
var prototypeType = typeof Object.prototype;
console.log(prototypeType);
// now let's examine it!
var hasOwn = Object.prototype.hasOwnProperty("hasOwnProperty");
console.log(hasOwn);
function StudentReport() {
var grade1 = 4;
var grade2 = 2;
var grade3 = 1;
this.getGPA = function() {
return (grade1 + grade2 + grade3) / 3;
};
}
var myStudentReport = new StudentReport();
for(var x in myStudentReport) {
if(typeof myStudentReport[x] !== "function") {
console.log("Muahaha! "+myStudentReport[x]);
}
}
console.log("Your overall GPA is "+myStudentReport.getGPA());