19/30 - Is it possible to do literal object notation instead?


#1

Is there a way to create a new Penguin object using the literal object notation?

Ex: var penguin = {
name: "Ping"
};

// 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;
    this.numLegs = 2;
}

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

 **var penguin = new Penguin();**
** penguin.name = "Ping";**

penguin.sayName();


#2

@vinhcodecade,
== the Book ==
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Use google search
== discussions / opinions ==
javascript can i add a prototype chain to a literal notated object site:stackoverflow
for instance
http://stackoverflow.com/questions/7015693/how-to-set-the-prototype-of-a-javascript-object-that-has-already-been-instantiat

=============================================

J a v a S c r i p t and it's == p r o t o t y p e - C h a i n ==

They want you to set up the chain:

        OBJECT
  Object.prototype
           ^
           |
  Animal.prototype  (( has the sayName Method))
           |                              ^
           |                              | 
           |                    Animal Class-Constructor
           ^                   | with this constructor
           |                   |  you can create Instance's of Animal
           |
           |    <<== You define this link in the Chain using
           ^            Penguin.prototype = new Animal();
           |
  Penguin.prototype ((is empty))
           |               ^
           |               | 
           |          Penguin Class-constructor
           ^                   | with this constructor
           |                   |  you can create Instance's of Penguin
   /Instance /      <---   using new Penguin("aName");
   | of      |
   | Penguin |
    The Penguin-Instance has access
     to Animal.prototype.sayName Method
     via the Penguin-prototype which is
      -chained- to the Animal-prototype.

===========================================================


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.