JavaScript code reuse mode

Source: Internet
Author: User

Transferred from: http://segmentfault.com/a/1190000000762220

Code reuse and its principles

代码复用, as the name implies, is to re-use part of the code that has been written, or even all of it, to build a new program. When we talk about code reuse, the first thing we can think of is 继承性 . The code reuse principle is:

优先使用对象组合,而不是类继承

In JS, because there is no concept of class, so the concept of the instance is not much significance, JS object is a simple key-value pairs, you can dynamically create and modify them.

But in js , we can new instantiate an object using constructors and operators, which are syntactically similar to other programming languages that use classes.

For example:

var trigkit4 = new Person();

jsIt seems to be Person a class when calling a constructor, but it is actually still a function, which gives us some assumptions about how to develop ideas and inheritance patterns on the basis of classes, which we can call "class-inheriting patterns."

The traditional inheritance pattern is the need for class keywords, we assume that the class-based inheritance pattern is 现代继承模式 , this is a kind of pattern that does not need to be considered in a class way.

Class-Type Inheritance mode

Take a look at the following two constructors Parent() and Child() examples:

<ScriptType="Text/javascript" > functionParent(name) {this.name = name | | function () {return this.name;} function Child //creates an object with the parent constructor and assigns the object to the child prototype for inheritance function inherit  (c,p) {c.prototype = new P (); //invoke the declared inheritance function inherit (child,parent); SCRIPT>           

When new Child() you create an object using a statement, it Parent() obtains its functionality from the instance through the prototype, such as:

var kid = new Child();kid.say();//Allen
Prototype chain

Discussing how the prototype chain works in class-inheritance mode, we see the object as a block somewhere in memory that contains data and references to other blocks. When you new Parent() create an object with a statement, you create a block such as the left, which holds the name property, and if you want to access the say() method, we can access the right chunk by means of an implicit link to the constructor Parent() 's prototype (prototype) property. __proto__ Parent.prototype.

So what happens when I use the var kid = new Child() create new object? Such as:

new Child()an object created with a statement __proto__ is almost empty except for an implicit link. In this case, __proto__ point to the inherit() new Parent() object created by using the statement in the function

When executed kid.say() , because there is no method for the block object in the lower left corner, say() He will query the middle chunk object through the prototype chain, however, there is no method for the middle chunk object, say() so he then queries the prototype chain to the rightmost chunk object, and the object has a say() method. Are you done?

Execution here is not complete, referenced in the say() method, this point to the this.name constructor created by the object, here, it points new Child() to the block, however, new Child() there is no name attribute, for this, will query the middle block, and the middle block just have name attribute, the query for the prototype chain is complete.

For a more detailed discussion, please check out my article: JavaScript Learning Summary (v) prototype and prototype chain detailed

Share prototypes

The rule of this pattern is that reusable members should be transferred to the prototype instead of being placed in this. Therefore, in the purpose of inheritance, anything worthy of inheritance should be implemented in the prototype. Therefore, you can set the prototype of the child object to be the same as the prototype of the parent object, as shown in the following example:

function inherit(C,P){    C.prototype = P.prototype;}

The child object and the parent object share the same prototype and can access the say() method equally. However, the child object does not inherit the name property

Prototype inheritance

Prototype inheritance is a "modern" class-free inheritance pattern. See the following example:

<script type="text/javascript"> //要继承的对象 var parent = { name : "Jack" //这里不能有分号哦 }; //新对象 var child = Object(parent); alert(child.name);//Jack</script>

In prototype mode, you do not need to use object literals to create a parent object. As the following code shows, you can use constructors to create a parent object, so that its properties and the properties of the constructor's prototype will be inherited.

<ScriptType="Text/javascript" > //parent constructor function person () {this.name =  "TRIGKIT4"; } //added to the prototype properties Person.prototype.getName = function () {return this.name;}; //Create a new Person class object var obj = new Person (); //inherit var kid = Object (obj); alert (Kid.getname ()); //trigkit4</SCRIPT>   

In this mode, you can select a prototype object that inherits only existing constructors. objects inherit from the object, regardless of how the parent object is created, as in the following instance:

<ScriptType="Text/javascript" > Parent constructorfunctionPerson(){THIS.name = "TRIGKIT4";} //added to the prototype properties Person.prototype.getName =  function () {return this.name; }; //Create a new Person class object var obj = new Person (); //inherit var kid = Object ( Person.prototype); console.log (typeof kid.getname);  function, because it console.log in the prototype (typeof kid.name); //undefined, because only the prototype is inherited </script>  
Inherit the functionality of an object

Use the concept of the constructor chain and the Function.apply () method to simulate the traditional class inheritance behavior in JS:

 <Script>        functionOldobject(param1) {THIS.PARAM1 =param1;This.getparam =function() {Returnthis.param1; } }functionNewObject(PARAM1,PARAM2) {This.param2 =param2;THIS.GETPARAM2 =function() {ReturnTHIS.PARAM2; }; Oldobject.apply (Thisarguments); this.getallparams = function Span class= "Hljs-params" > () {return this.getparam () + this.getparam2 ();}} window.onload = function  () {Newobject.prototype = new oldobject (); var obj = new newObject ( "value1", Span class= "hljs-string" > "value2"); //print out two parameters alert (Obj.getallparams ());}; </SCRIPT>         

First, in newObject the constructor, oldObject a method is invoked apply , passing in a reference to the new object and an array of arguments. applymethod inherits from Function object

new oldObject();

This is js an example of a chain of constructor functions. When a newObject new instance is created, the newObject methods and properties of the old object are inherited in such a way.

JavaScript code reuse mode

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.