JavaScript Object-Oriented Programming (1)
Declare objects directly
Var dog = {name: 'benji ', talk: function () {alert ('Woof, Woof! ') ;}}; Alert (typeof (dog); dog. talk ();
In this way, the dog object has such attributes and talk functions.
You can also use constructors.
// -------- Constructor -------- function Hero () {this. occupation = 'ninja '; // occupation is samurai} var hero = new Hero (); // create a new object alert (hero. occupation); // call attributes
The constructor can also contain parameters.
// --------- Constructor with parameters ----------- function Hero (name) {this. name = name; this. occupation = 'ninja '; // the occupation is a warrior // behavior this. whoAreYou = function () {return "I'm" + this. name + "and I'm a" + this. occupation;} var h1 = new Hero ('angelo'); var h2 = new Hero ('donatello '); alert (h1.whoAreYou ());