Search

11/18/2008

Popular JavaScript Framework Libraries: An Overview - Part 2 / Page 2

Popular JavaScript Framework Libraries: An Overview - Part 2 / Page 2

YAHOO.lang.extend provides a simple mechanism for setting up the prototype, constructor and superclass properties for objects that are extending other objects. It also prevents the constructor of the extended object (i.e., the superclass) from being executed twice. Let's take a look at an example. The following code assigns a namespace for our classes, creates a Person superclass and a child Investor class that inherits from it. You can see that code conciseness is being traded for clarity. Depending on your personal views, you may prefer a $ sign over YAHOO.test:


YAHOO.namespace("test");

YAHOO.test.Person = function(name) {
alert("Hi, I'm " + name);
};

YAHOO.test.Person.prototype.speak = function(words) {
alert(words);
};

YAHOO.test.Investor = function(name) {
// chain the constructors
YAHOO.test.Investor.superclass.constructor.call(this, name);
alert("Hi, my name is " + name + " and I'm an investor.");
};

// Investor extends Person. Must be done immediately after the Investor constructor
YAHOO.lang.extend(YAHOO.test.Investor, YAHOO.test.Person);

YAHOO.test.Investor.prototype.speak = function(words) {
// chain the method
YAHOO.test.Investor.superclass.speak.call(this, words);
alert("It has not been a good year for investors!");
};

var investor = new YAHOO.test.Investor("Bill");
investor.speak("I don't feel so good.");

沒有留言: