24h購物| | PChome| 登入
2012-05-12 09:22:10| 人氣719| 回應0 | 上一篇 | 下一篇

[JavaScript] Introduction to Objects II

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

Objects, Objects Everywhere

// complete these definitions so that they will have
// the appropriate types
var anObj = { job: "I'm an object!" };
var aNumber = 42;
var aString = "I'm a string!";

console.log(typeof(anObj)); // should print "object"
console.log(typeof(aNumber)); // should print "number"
console.log(typeof(aString)); // should print "string"


var myObj = {
    // finish myObj
    name: "Morris",
};

console.log( myObj.hasOwnProperty('name') ); // should print true
console.log( myObj.hasOwnProperty('nickname') ); // should print false
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};
for(var property in nyc) {
    console.log(property);
}
// write your for-in loop here


You Down With OOP?

function Dog (breed) {
  this.breed = breed;
};

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


function Cat(name, breed) {
    this.name = name;
    this.breed = breed;
}

// let's make some cats!
var cheshire = new Cat("Cheshire Cat", "British Shorthair");
var gary = new Cat("Gary", "Domestic Shorthair");

// add a method "meow" to the Cat class that will allow
Cat.prototype.meow = function() {
    console.log("Meow!");
}
// all cats to print "Meow!" to the console
cheshire.meow();
gary.meow();
// add code here to make the cats meow!


Inheriting a Fortune

// create your Animal class here
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}

// create the sayName method for Animal
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
}
function Penguin(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Penguin.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
}
// provided code to test above constructor and method
var penguin = new Penguin("Captain Cook", 2);
penguin.sayName();


function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
}

// create your Emperor class here and make it inherit from Penguin
function Emperor(name) {
    this.name = name;
}
Emperor.prototype = new Penguin();

// create an "emperor" object and print the number of legs it has
var emperor = new Emperor("ee");
console.log(emperor.numLegs);



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

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