The code is as follows:
But we cannot reuse this object. How can we use this object as a prototype?
First of all, it is impossible to have a constructor method in a JSON object, so let's make a simple "factory" and write a method specifically responsible for creation.
But through this method we found that we cannot use People as a prototype. Let us review: Javascript study notes 7— —In this article about the principle of prototype chain, let’s think about this process:
var p=new People();==>p.__proto__=People.prototype. So when we p.SayHello(), we will go to People.prototype to find it, but we can't find anything.
If People.prototype.SayHello=function(){} can solve this problem. But we know that only functions can have prototypes.
So let’s think about the previous derivation formula, how can we make p.SayHello()? It would be nice if we could p.__proto__=People. Then we come up with a way:
Since in new, the __proto__ of a certain object can only be equal to the prototype of a certain function, we set a function X and let p.__proto__=X.prototype, we Then set X.prototype=People. The relationship is as follows:
This is equivalent to using X to make an intermediate variable, allowing us to access the internal properties of the JSON object. But isn’t this inelegant? Every time we create an object, we need to write such an auxiliary function. Well, let’s encapsulate this process:
var Factory = {
CreatePeople : function (className,name,age) {
var temp = function () {
className.Create(name, age);
};
temp.prototype = className;
var result = new temp();
return result;
}
};
var people = Factory.CreatePeople(People,"kym",21);
people.SayHello();
But this also has a disadvantage, that is, every time I add a class, I need to register a new method in the Factory. This is very troublesome. I did it a long time ago How to play with: call and apply I mentioned the difference between call and apply. Because the parameters here are not fixed, we cannot list them one by one, so we can use apply here to improve this method: