Code rewrite for the factory pattern in the previous chapter
function Human (name, sex) {
this.name = name;
This.sex = sex;
This.say = function () {
alert (this.name);
}
var man = new Human ("Hanwu", "male");
var woman = new Human ("Heavenly Queen", "female");
Not to human. His first letter was capitalized. This is a grammatical convention. Constructors should always start with an uppercase letter, rather than a constructor, which starts with a lowercase letter to differentiate between constructors and constructors.
To create an instance of human, you must use the new operator. This results in the following four steps:
1. Create a new object or variable.
2. Assign a constructor's scope to a new variable or new object.
3. Execute the code in the constructor
4. Returns the new object.
1 alert (man instanceof Object);//true
2 alert (man instanceof Human); True
3 Alert (woman instanceof Object); True
4 alert (woman instanceof Human); True
True here is a good illustration of the fact that creating a custom constructor means that his instance can be represented as a particular type in the future. This is where the Korean model is better than the factory model.
Still, the constructor has its own flaws, or inadequate.
There is a method named Say () in both man and woman, and they have exactly the same functionality. But these two methods are not created by the same function () instance.
1 function Human (name, sex) {
2 this.name = name;
3 this.sex = sex;
4 This.say = new Function ("alert (this.name);");
5}
This means that if you need n instances, you will create n say function () instances. This will still cause waste of resources.
Continue to optimize the code above so that the Say () method is created only once. Share a reference.
function Human (name, sex) {
this.name = name;
This.sex = sex;
This.say = say;
function Say () {
alert (this.name);
}
Because say contains a pointer to a function, an instance of human shares the same say () function in the global scope. But this is unacceptable,
Because if the system is larger, there will be a lot of global variables, inadvertently there will be the risk of getting rid of. And the objects we encapsulate have no encapsulation.
And then there's the prototype model. The next chapter goes on to say prototype mode.