The object model in JavaScript is not widely known. I once wrote a blog about them. One of the reasons why it is not well-known is that JavaScript is the only one among these widely used languages that can be inherited through prototypes. However, I think another reason is that this object model is very complex and difficult to explain. Why is it so complicated and confusing? That's because JavaScript tries to hide its traditional object-oriented characteristics - ultimately leading to its dual personality (Translator's note: The author means that JavaScript has both process-oriented and object-oriented characteristics).
I think it is precisely because of the incomprehensible and use of JavaScript object models that some languages like CoffeeScript, Dart and TypeScript have emerged that can generate JS code through compilation.
The predecessors of JavaScript and the diehards believe that JavaScript has a better object model and feel sorry for it being forgotten by everyone. Even JavaScript expert Nicholas Zakas welcomes the new class syntax added in ECMAScript 6 - just some modifications to the syntax of prototype style. In other words, traditional OOP won.
A bold idea
However, let's make a joke: we imagine traveling to the past, when traditional object-oriented programming was not widely accepted as it is now. On the contrary, the prototype-based inheritance model has been widely accepted by everyone. What will happen if this happens? What kind of design patterns will we get in the end?
Let's imagine again: What if JavaScript has no constructor or no new keyword? What will things become? Let's push it to the previous re-start. :)
First, the first thing is that in JavaScript, we can use object literals to create a new object. As shown below:
var felix = {
name: 'Felix',
greet: function(){
('Hello, I am ' + + '.');
}
};
Next, suppose we want to generalize the greet function, extract it, and put it in a general position, so that we can create multiple objects to share the same greet method. How to achieve it?
We have several options, let’s start with mixin first.
1. Mixin(Augmentation)
In JavaScript, it is very simple to mix properties. You just need to copy the properties of the mixed object into the object you want to mix it into. We will use an "augment" function to implement it, and you will understand it by looking at the code:
var Dude = {
greet: function(){
('Hello, I am ' + + '.')
}
};
var felix = { name: 'Felix' };
augment(felix, Dude);//Copy the attributes in Dude into felix, that is, mix in (mixin)
In the above code, the augment function mixes the properties of the Dude object into felix. In many JS libraries, the augment function is called extend. I don't like to use extend because some languages use extend to represent inheritance, so I'm confused. I prefer to use "augment" because in fact this approach is not inheritance, and the syntax augment (felix, Dude) has clearly shown that you have used the properties in Dude to expand felix rather than inherit.
Maybe you have guessed the code of augment long ago, that's right, it's very simple. As shown below:
function augment(obj, properties){
for (var key in properties){
obj[key] = properties[key];
}
}
2. Object cloning (Cloning)
An alternative to mixin is to clone the Dude object first, and then set the name attribute to the cloned object. As shown below:
var Dude = {
greet: function(){
('Hello, I am ' + + '.');
}
}
var felix = clone(Dude);//Clone the Dude object
= 'Felix';
The only difference between these two methods is the order in which attributes are added. If you want to override some of the methods in the cloned object, you can consider using this method.
var felix = clone(Dude);
= 'Felix';
= function(){
('Yo dawg!');
};//Overwrite the greet method
If you want to call the parent class method, it is also very simple - use the apply function, as shown below
= function(){
(this);
++;
}
This is much better than prototype-style code, because you don't have to use the constructor's .prototype property - we won't use any constructors.
The following is the implementation of the clone function:
function clone(obj){
var retval = {};//Create an empty object
augment(retval, obj);//Copy attributes
return retval;
}
3. Inheritance
Finally, it is inheritance. In my opinion, inheritance is overrated, but inheritance does have some advantages over object expansion in sharing properties between "instance objects". Let's write an inherit function that takes an object as a parameter and returns a new object inherited from that object.
var felix = inherit(Dude);
= 'Felix';
Using inheritance, you can create multiple child objects inherited from the same object, which can inherit the properties of the parent object in real time. As shown in the following code,
var garfield = inherit(Dude);//garfield inherits from Dude
= function(){//Add a new method to Dude walk
('Step, step');
};
(); // prints "Step, step"
(); // also prints "Step, step"
Inherit function is used for inheriting the prototype object
function inherit(proto){
if (){
// Use the method in ES5
return (proto);
}else if({}.__proto__){
//Use non-standard attribute __proto__
var ret = {};
ret.__proto__ = proto;
return ret;
}else{
//If neither is supported, use constructor inheritance
var f = function(){};
= proto;
return new f();
}
}
The above code doesn't look very good, because we use feature monitoring to determine which of the three methods we use.
But how to use the constructor (that is, the initialization method)? How do you share the initialization code between instance objects? In some cases, if you only need to set some properties for the object, the initialization function is not necessary, as in our example above. But if you have more initialization code, you might make a convention, such as: use an initialization method called initialize. Let's assume that a method called initialize is defined in Dude, as follows
var Dude = {
initialize: function(){
= 0;
},
greet: function(){
('Hello, I am ' + + '.');
++;
}
}
Then, you can initialize the object like this
var felix = clone(Dude);
= 'Felix';
(); or it can
var felix = { name: 'Felix' };
= 'Felix';
augment(felix, Dude);
();Well enough
var felix = inherit(Dude);
= 'Felix';
();Conclusion
I mean that with the three functions defined above - augment, clone and inherit, you can do whatever you want to do with objects in JavaScript without having to use constructors and new keywords. I think the semantics embodied by these three functions are simpler and closer to the underlying object system of JavaScript. (End)^_^
I think it is precisely because of the incomprehensible and use of JavaScript object models that some languages like CoffeeScript, Dart and TypeScript have emerged that can generate JS code through compilation.
The predecessors of JavaScript and the diehards believe that JavaScript has a better object model and feel sorry for it being forgotten by everyone. Even JavaScript expert Nicholas Zakas welcomes the new class syntax added in ECMAScript 6 - just some modifications to the syntax of prototype style. In other words, traditional OOP won.
A bold idea
However, let's make a joke: we imagine traveling to the past, when traditional object-oriented programming was not widely accepted as it is now. On the contrary, the prototype-based inheritance model has been widely accepted by everyone. What will happen if this happens? What kind of design patterns will we get in the end?
Let's imagine again: What if JavaScript has no constructor or no new keyword? What will things become? Let's push it to the previous re-start. :)
First, the first thing is that in JavaScript, we can use object literals to create a new object. As shown below:
Copy the codeThe code is as follows:
var felix = {
name: 'Felix',
greet: function(){
('Hello, I am ' + + '.');
}
};
Next, suppose we want to generalize the greet function, extract it, and put it in a general position, so that we can create multiple objects to share the same greet method. How to achieve it?
We have several options, let’s start with mixin first.
1. Mixin(Augmentation)
In JavaScript, it is very simple to mix properties. You just need to copy the properties of the mixed object into the object you want to mix it into. We will use an "augment" function to implement it, and you will understand it by looking at the code:
Copy the codeThe code is as follows:
var Dude = {
greet: function(){
('Hello, I am ' + + '.')
}
};
var felix = { name: 'Felix' };
augment(felix, Dude);//Copy the attributes in Dude into felix, that is, mix in (mixin)
In the above code, the augment function mixes the properties of the Dude object into felix. In many JS libraries, the augment function is called extend. I don't like to use extend because some languages use extend to represent inheritance, so I'm confused. I prefer to use "augment" because in fact this approach is not inheritance, and the syntax augment (felix, Dude) has clearly shown that you have used the properties in Dude to expand felix rather than inherit.
Maybe you have guessed the code of augment long ago, that's right, it's very simple. As shown below:
Copy the codeThe code is as follows:
function augment(obj, properties){
for (var key in properties){
obj[key] = properties[key];
}
}
2. Object cloning (Cloning)
An alternative to mixin is to clone the Dude object first, and then set the name attribute to the cloned object. As shown below:
Copy the codeThe code is as follows:
var Dude = {
greet: function(){
('Hello, I am ' + + '.');
}
}
var felix = clone(Dude);//Clone the Dude object
= 'Felix';
The only difference between these two methods is the order in which attributes are added. If you want to override some of the methods in the cloned object, you can consider using this method.
Copy the codeThe code is as follows:
var felix = clone(Dude);
= 'Felix';
= function(){
('Yo dawg!');
};//Overwrite the greet method
If you want to call the parent class method, it is also very simple - use the apply function, as shown below
Copy the codeThe code is as follows:
= function(){
(this);
++;
}
This is much better than prototype-style code, because you don't have to use the constructor's .prototype property - we won't use any constructors.
The following is the implementation of the clone function:
Copy the codeThe code is as follows:
function clone(obj){
var retval = {};//Create an empty object
augment(retval, obj);//Copy attributes
return retval;
}
3. Inheritance
Finally, it is inheritance. In my opinion, inheritance is overrated, but inheritance does have some advantages over object expansion in sharing properties between "instance objects". Let's write an inherit function that takes an object as a parameter and returns a new object inherited from that object.
Copy the codeThe code is as follows:
var felix = inherit(Dude);
= 'Felix';
Using inheritance, you can create multiple child objects inherited from the same object, which can inherit the properties of the parent object in real time. As shown in the following code,
Copy the codeThe code is as follows:
var garfield = inherit(Dude);//garfield inherits from Dude
= function(){//Add a new method to Dude walk
('Step, step');
};
(); // prints "Step, step"
(); // also prints "Step, step"
Inherit function is used for inheriting the prototype object
Copy the codeThe code is as follows:
function inherit(proto){
if (){
// Use the method in ES5
return (proto);
}else if({}.__proto__){
//Use non-standard attribute __proto__
var ret = {};
ret.__proto__ = proto;
return ret;
}else{
//If neither is supported, use constructor inheritance
var f = function(){};
= proto;
return new f();
}
}
The above code doesn't look very good, because we use feature monitoring to determine which of the three methods we use.
But how to use the constructor (that is, the initialization method)? How do you share the initialization code between instance objects? In some cases, if you only need to set some properties for the object, the initialization function is not necessary, as in our example above. But if you have more initialization code, you might make a convention, such as: use an initialization method called initialize. Let's assume that a method called initialize is defined in Dude, as follows
Copy the codeThe code is as follows:
var Dude = {
initialize: function(){
= 0;
},
greet: function(){
('Hello, I am ' + + '.');
++;
}
}
Then, you can initialize the object like this
Copy the codeThe code is as follows:
var felix = clone(Dude);
= 'Felix';
(); or it can
var felix = { name: 'Felix' };
= 'Felix';
augment(felix, Dude);
();Well enough
var felix = inherit(Dude);
= 'Felix';
();Conclusion
I mean that with the three functions defined above - augment, clone and inherit, you can do whatever you want to do with objects in JavaScript without having to use constructors and new keywords. I think the semantics embodied by these three functions are simpler and closer to the underlying object system of JavaScript. (End)^_^