面向对象的JavaScript-002
1.
1 <script type="text/javascript"> 2 3 // Define the Person constructor 4 var Person = function(firstName) { 5 this.firstName = firstName; 6 }; 7 8 // Making sure that this points to the right thing regardless of how the object is instantiated can be difficult. However, there is a simple idiom to make this easier. 9 var Person = function(firstName) { 10 if (this instanceof Person) { 11 this.firstName = firstName; 12 } else { 13 return new Person(firstName); 14 } 15 } 16 17 // Add a couple of methods to Person.prototype 18 Person.prototype.walk = function(){ 19 console.log("I am walking!"); 20 }; 21 22 Person.prototype.sayHello = function(){ 23 console.log("Hello, I'm " + this.firstName); 24 }; 25 26 // Define the Student constructor 27 function Student(firstName, subject) { 28 // Call the parent constructor, making sure (using Function#call) 29 // that "this" is set correctly during the call 30 Person.call(this, firstName); 31 32 // Initialize our Student-specific properties 33 this.subject = subject; 34 } 35 36 // Create a Student.prototype object that inherits from Person.prototype. 37 // Note: A common error here is to use "new Person()" to create the 38 // Student.prototype. That's incorrect for several reasons, not least 39 // that we don't have anything to give Person for the "firstName" 40 // argument. The correct place to call Person is above, where we call 41 // it from Student. 42 Student.prototype = Object.create(Person.prototype); // See note below 43 44 // Set the "constructor" property to refer to Student 45 Student.prototype.constructor = Student; 46 47 // Replace the "sayHello" method 48 Student.prototype.sayHello = function(){ 49 console.log("Hello, I'm " + this.firstName + ". I'm studying " 50 + this.subject + "."); 51 }; 52 53 // Add a "sayGoodBye" method 54 Student.prototype.sayGoodBye = function(){ 55 console.log("Goodbye!"); 56 }; 57 58 // Example usage: 59 var student1 = new Student("Janet", "Applied Physics"); 60 student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." 61 student1.walk(); // "I am walking!" 62 student1.sayGoodBye(); // "Goodbye!" 63 64 // Check that instanceof works correctly 65 console.log(student1 instanceof Person); // true 66 console.log(student1 instanceof Student); // true 67 68 // 如果 On older JavaScript engines without Object.create, one can either use a "polyfill" (aka "shim", see the linked article), or one can use a function that achieves the same result, such as: 69 function createObject(proto) { 70 function ctor() { } 71 ctor.prototype = proto; 72 return new ctor(); 73 } 74 75 // Usage: 76 Student.prototype = createObject(Person.prototype);
You can do anything you set your mind to, man!