Home > Web Front-end > JS Tutorial > body text

JavaScript's object-oriented approach can be implemented without using the constructor (Constructor) new keyword_javascript tips

WBOY
Release: 2016-05-16 17:43:58
Original
1040 people have browsed it

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 of these widely used languages ​​​​that implements inheritance through prototypes. However, I think another reason is that this object model is very complex and difficult to explain. Why is it so complex 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 difficulty of understanding and using the JavaScript object model that there are languages ​​like CoffeeScript, Dart and TypeScript that can generate JS code through compilation.

JavaScript’s predecessors and die-hards believe that JavaScript has a better object model and lament that it will be forgotten by everyone. Even JavaScript expert Nicholas Zakas welcomes the new class syntax added in ECMAScript 6 - which is just a modification of the prototypal style syntax. In other words, traditional OOP wins.

A bold idea
However, let us make an idea in a joking way: we imagine traveling to the past, when traditional object-oriented programming was not as good as it is now. This is widely accepted by everyone. On the contrary, the prototype-based inheritance model has been widely accepted by everyone. What will happen? What design patterns will we end up with?

Let’s imagine again: What would happen if JavaScript had no constructor or no new keyword? What will happen next? Let's push back to the past. :)

First of all, the first thing, in JavaScript, we can use object literals to create a new object. As shown below:

Copy the code The code is as follows:

var felix = {
name : 'Felix',
greet: function(){
console.log('Hello, I am ' this.name '.');
}
};

Next, suppose we want to generalize the greet function, extract it and put it in a general location, so that we can create multiple objects to share the same greet method. How to achieve this?
We have several options, let’s start with mixin.

1. Mixin(Augmentation)
In JavaScript language, mixing attributes is very simple. You just need to copy the properties of the mixed object to the object you want to mix in. We will use an "augment" function to implement it, you will understand by looking at the code:
Copy the code The code is as follows:

var Dude = {
greet: function(){
console.log('Hello, I am ' this.name '.')
}
};
var felix = { name: 'Felix' };
augment(felix, Dude);//Copy the attributes in Dude to felix, that is, 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 using extend because some languages ​​use extend to express inheritance, which makes me confused. I prefer to use "augment" to express it, because in fact this approach is not inheritance, and the syntax augment(felix, Dude) already clearly shows that you are extending felix with the attributes in Dude, rather than inheriting.

Maybe you have already guessed that the augment code is implemented, yes, it is very simple. As shown below:
Copy code The code is as follows:

function augment(obj, properties){
for (var key in properties){
obj[key] = properties[key];
}
}

2. Object 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 code The code is as follows:

var Dude = {
greet : function(){
console.log('Hello, I am ' this.name '.');
}
}
var felix = clone(Dude);//Clone the Dude object
felix.name = 'Felix';

The only difference between the two methods is the order in which the properties are added. You may consider using this technique if you want to override certain methods in the cloned object.
Copy code The code is as follows:

var felix = clone(Dude);
felix .name = 'Felix';
felix.greet = function(){
console.log('Yo dawg!');
};//Override greet method

If you want to call the method of the parent class, it is also very simple - use the apply function, as shown below
Copy the code The code is as follows:

felix.greet = function(){
Dude.greet.apply(this);
this.greetingCount ;
}

This is much better than prototype-style code because you don’t have to use the .prototype property of the constructor - we won’t use any constructors.
The following is the implementation of the clone function:
Copy code The 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. Inheritance is overrated in my opinion, but inheritance does have some advantages over object expansion in terms of sharing properties between "instance objects". Let's write an inherit function that takes an object as a parameter and returns a new object that inherits from that object.
Copy code The code is as follows:

var felix = inherit(Dude);
felix .name = 'Felix';

Using inheritance, you can create multiple child objects that inherit from the same object. These child objects can inherit the properties of the parent object in real time. As shown in the code below,
Copy code The code is as follows:

var garfield = inherit( Dude);//garfield inherits from Dude
Dude.walk = function(){//Add a new method to Dude walk
console.log('Step, step');
};
garfield.walk(); // prints "Step, step"
felix.walk(); // also prints "Step, step"

Prototype-based is used in the inherit function Inheritance of objects
Copy code The code is as follows:

function inherit(proto){
if (Object.create){
//Use the Object.create method in ES5
return Object.create(proto);
}else if ({}.__proto__){
//Use Non-standard attribute __proto__
var ret = {};
ret.__proto__ = proto;
return ret;
}else{
//If neither is supported, use the constructor Inherit
var f = function(){};
f.prototype = proto;
return new f();
}
}

the above The code doesn't look good, that's because we use feature monitoring to determine which of the 3 methods to use.

But, how to use the constructor method (that is, the initialization method)? How do you share initialization code between instance objects? In some cases, if you only need to set some properties for the object, then the initialization function is not necessary, as in our example above. But if you have more initialization code, you might make a convention, for example: use an initialization method called initialize. We assume that a method called initialize is defined in Dude, as follows:
Copy the code The code is as follows:

var Dude = {
initialize: function(){
this.greetingCount = 0;
},
greet: function(){
console.log('Hello, I am ' this.name '.');
this.greetingCount ;
}
}

Then, you can initialize the object like this
Copy code The code is as follows:

var felix = clone(Dude);
felix.name = 'Felix';
felix.initialize(); or
var felix = { name: 'Felix' } ;
felix.name = 'Felix';
augment(felix, Dude);
felix.initialize();Also
var felix = inherit(Dude);
felix.name = 'Felix';
felix.initialize();Conclusion

I mean that through the three functions defined above - augment, clone and inherit, you can do anything with objects in JavaScript What you want to do without having to use constructors and the new keyword. I think the semantics embodied by these three functions are simpler and closer to the underlying object system of JavaScript. (End)^_^
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template