24h購物| | PChome| 登入
2012-05-12 09:34:41| 人氣535| 回應0 | 上一篇 | 下一篇

[JavaScript] Introduction to Objects II

推薦 0 收藏 0 轉貼0 訂閱站台

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());

台長: Morris
人氣(535) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: [學習]JavaScript |
此分類下一篇:[JavaScript] HTML 輸出練習
此分類上一篇:[JavaScript] Introduction to Objects II

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文