most near saw "You do not know the JavaScript" feeling very deep, especially in the concept of the commissioned design, it is to open the door of the new World to me, and you share it.
Requirements:
There is a people object that requires the property name and the Age,sayyourself method to print the two variables.
There is a student object that requires a property Grade,saygrade method to print the two variables.
first of all, object-oriented design: Emphasizing the relationship between entity and entity
The idea that is usually inherited by archetype. The code is as follows:
*
* Object-oriented design pattern
* Prototype inheritance
* Student inheritance
people
/Function people (age,name) {
this.age = age;
this.name = name;
Inheritance method sayyourself
People.prototype.sayYourSelf = function () {
console.log ("Your name: +this.name+"; Your age "+ this.age);
}
function Student (age,name,grade) {
//change the value in people
People.call (this,age,name);
This.grade = grade;
This.saygrade = function () {
console.log ("Your Grade:" +this.grade);
}
Create an association between people and Student
student.prototype = object.create (people.prototype);
var human = new People ("Joy");
Human.sayyourself ()//
var studenta = new Student ("Cindy", "Junior");
Studenta.sayyourself ()//
Such code seems to solve the problem of inheritance, but it is very cumbersome, the following is my recommendation for the delegate-oriented, and object-related design patterns.
strongly recommend ....
Object-associated design pattern: Focus only on association relationships between objects
/* Object Association design Pattern ----The association relationship between objects and objects
* *
student Inherits people/
var person
= {
sayyourself: function () {
console.log ("Your name:" +this.name+); Your age "+ this.age);
},
init:function (name,age) {
this.name = name;
This.age = age;
}
;
Create Student Object Association people
var Student = object.create (person);
Defines Student internal method
Student.saygrade = function () {
console.log ("Your Grade:" +this.grade);
Student.setgrade = function (grade) {
this.grade = grade;
}
Creation and initialization is divided into two steps
var HumanA = object.create (person);
Humana.init ("Tom");
var studentb = object.create (Student);
Studentb.setgrade ("Junior");
Compare the two code, the advantage is more obvious.
Advantages:
1. Make the code look more concise.
2. Avoid an ugly explicit pseudo polymorphic invocation (People.call), instead of a relatively simple delegate invocation (Studentb.init).
3. The code is much easier to understand.
4. Object associations can better support the focus on the separation principle (separation of concerns), and creation and initialization do not need to be merged into one step.
Anyway, today to share here ~ hee ~ Goodnight ~