Object-oriented _javascript techniques for JavaScript are also implemented without the constructor (constructor) New keyword

Source: Internet
Author: User
Tags object model
The object model in JavaScript is not widely known. I have written a blog about them. One reason why it is not well known is that JavaScript is the only one of these widely used languages that is inherited through a prototype (prototype). However, I think another reason is that the object model is very complex and difficult to explain. Why was it so complicated and confusing? That's because JavaScript tries to hide its traditional object-oriented features--which ultimately leads to its dual personality: the author means that JavaScript has both process-oriented features and object-oriented features.

I think it is because the JavaScript object model is difficult to understand and use, there are some like Coffeescript,dart and typescript these compiled can generate JS code language.

The predecessors of JavaScript and the die-hards believe that JavaScript has a better object model and regrets that it will be forgotten. Even JavaScript expert Nicholas Zakas welcomes the new class syntax added to ECMAScript 6--just a few modifications to the syntax of the prototype style (Prototypal style). In other words, traditional oop has won.

a bold idea.
But let's make a joke of the idea that we're supposed to travel through the past, when traditional object-oriented programming isn't as widely accepted as it is now, and on the contrary, the prototype inheritance model has been widely accepted. What happens then? What kind of design patterns do we eventually get?

Let's imagine: What if JavaScript doesn't have a constructor or a new keyword? What is it going to become? Let's push it back to the past. :)

First, first thing, in JavaScript, we can create a new object using the literal volume of the object. As shown below:
Copy Code code 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 position, so that we can create multiple objects to share the same greet method. How to achieve it?
We have several options, start with mixin.

1, mixed (object expansion) mixin (augmentation)
In the JavaScript language, mixing attributes is very simple. You only need to copy the properties of the object into the object you want to blend into. We'll use a "augment" function to implement it, and look at the code to see:
Copy Code code 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, Mix (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 express inheritance, so that I am confused. I prefer to use "augment" because in practice this is not an inheritance, and the syntax augment (Felix, Dude) has made it clear that you are expanding the Felix with the attributes in Dude, rather than inheriting it.

Maybe you already guessed it. Augment's code is implemented, yes, very simple. As shown below:
Copy Code code 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 before setting the Name property on the cloned object. As shown below:
Copy Code code as follows:

var Dude = {
Greet:function () {
Console.log (' Hello, I am ' + this.name + '. ');
}
}
var Felix = Clone (Dude);//Clone Dude Object
Felix.name = ' Felix ';

The only difference between the two methods is the order in which the attributes are added. If you want to overwrite some of the methods in the cloned object, you might consider using this technique.
Copy Code code as follows:

var Felix = Clone (Dude);
Felix.name = ' Felix ';
Felix.greet = function () {
Console.log (' Yo dawg! ');
};//greet method for writing and covering

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

Felix.greet = function () {
Dude.greet.apply (this);
this.greetingcount++;
}

This is much better than a prototype-style code because you don't have to use the constructor's. Prototype Property--we don't use any constructors.
The following is the implementation of the clone function:
Copy Code code as follows:

function Clone (obj) {
var retval = {};//Creates an empty object
Augment (retval, obj);//Copy Properties
return retval;
}

3. Inheritance (inheritance)
Finally, it is inherited. In my opinion, inheritance is overrated, but it does have some advantages over object expansion in terms of inheriting the properties shared between instance objects. Let's write a inherit function that receives an object as an argument and returns a new object that inherits from the object.
Copy Code code as follows:

var Felix = Inherit (Dude);
Felix.name = ' Felix ';

With inheritance, you can create multiple child objects that inherit from the same object, which can inherit the properties of the parent object in real time. As shown in the following code,
Copy Code code as follows:

var Garfield = Inherit (Dude);//garfield inherits from Dude
Dude.walk = function () {///Add new method to Dude walk
Console.log (' Step, Step ');
};
Garfield.walk (); Prints "Step and step"
Felix.walk (); Also prints "step and step"

Using a prototype object based inheritance in the Inherit function
Copy Code code as follows:

function inherit (proto) {
if (object.create) {
Using the Object.create method in ES5
Return object.create (proto);
}else if ({}.__proto__) {
Using nonstandard properties __proto__
var ret = {};
ret.__proto__ = Proto;
return ret;
}else{
If both are not supported, use the constructor to inherit
var f = function () {};
F.prototype = Proto;
return new F ();
}
}

The code above does not look good, because we use feature monitoring to determine which of the 3 ways to use.

But how do you use the construction method (i.e., the initialization method)? How do you share initialization code between instance objects? In some cases, if you only need to set some properties for an object, then the initialization function is not necessary, as in our example above. But if you have more initialization code, you may have a convention, for example: Using an initialization method called Initialize. We assume that a method called Initialize is defined in dude, as follows
Copy Code code 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 code as follows:

var Felix = Clone (Dude);
Felix.name = ' Felix ';
Felix.initialize (), or you can
var Felix = {name: ' Felix '};
Felix.name = ' Felix ';
Augment (Felix, Dude);
Felix.initialize (); You can also
var Felix = Inherit (Dude);
Felix.name = ' Felix ';
Felix.initialize (); epilogue

I'm saying that with the three functions defined above,--augment,clone and inherit, you can do whatever you want with the objects in JavaScript without having to use constructors and new keywords. I think the semantics of these three functions are simpler and closer to the JavaScript underlying object system. (end) ^_^
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.