1.
1<script type= "Text/javascript" >2 3 //Define the person constructor4 varperson =function(firstName) {5 This. FirstName =FirstName;6 };7 8 //Making sure that this points to the right thing regardless of what the object is instantiated can be difficult. However, there is a simple idiom to make this easier.9 varperson =function(firstName) {Ten if( This instanceofPerson ) { One This. FirstName =FirstName; A}Else { - return NewPerson (firstName); - } the } - - //Add A couple of methods to Person.prototype -Person.prototype.walk =function(){ +Console.log ("I am walking!"); - }; + APerson.prototype.sayHello =function(){ atConsole.log ("Hello, I ' m" + This. firstName); - }; - - //Define the Student constructor - functionStudent (FirstName, subject) { - //Call the parent constructor, making sure (using Function#call) in //That ' This ' is set correctly during the call -Person.call ( This, firstName); to + //Initialize our student-specific properties - This. Subject =subject; the } * $ //Create A Student.prototype object that inherits from Person.prototype.Panax Notoginseng //note:a Common error Here's to use ' new person ' to create the - //Student.prototype. That's incorrect for several reasons, not least the //That we don ' t has anything to give person for the "FirstName" + //argument. The correct place-to-call person are above, where we call A //it from Student. theStudent.prototype = Object.create (Person.prototype);//See Note below + - //Set the "constructor" property to refer to Student $Student.prototype.constructor =Student; $ - //Replace The "SayHello" method -Student.prototype.sayHello =function(){ theConsole.log ("Hello, I ' m" + This. FirstName + ". I ' m studying " -+ This. Subject + ".");Wuyi }; the - //Add A "Saygoodbye" method WuStudent.prototype.sayGoodBye =function(){ -Console.log ("goodbye!"); About }; $ - //Example Usage: - varStudent1 =NewStudent ("Janet", "Applied Physics"); -Student1.sayhello ();//"Hello, I ' m Janet." I ' m studying applied Physics. " AStudent1.walk ();//"I am walking!" +Student1.saygoodbye ();//"goodbye!" the - //Check that instanceof works correctly $Console.log (student1instanceofperson);//true theConsole.log (student1instanceofStudent);//true the the //if on older JavaScript engines without object.create, one can either use a "Polyfill" (aka "shim", see the linked art icle), or one can use a function that achieves the same result, such as: the functionCreateObject (Proto) { - functionctor () {} inCtor.prototype =Proto; the return Newctor (); the } About the //Usage: theStudent.prototype = CreateObject (Person.prototype);
Object-oriented JavaScript-002