Object-oriented in JS (several ways to create objects)

Source: Internet
Author: User
Tags prototype definition

1. Object-oriented programming (OOP) features :

Abstraction: Seizing the core issue

Encapsulation: Methods can only be accessed through objects

Inherit: Inherit new object from existing object

Polymorphism: Different forms of multiple objects

Note: This article refers to http://www.cnblogs.com/yuxingyoucan/p/5797142.html

I. Several ways to create objects

JavaScript creates objects simply by using built-in objects or a variety of custom objects and, of course, using JSON, but with a lot of notation and mixed use.

1. Factory-created objects: Encapsulated functions in object-oriented (built-in objects)

function Createperson (name) {   ///1, Raw    var obj=new Object ();   2, processing    obj.name=name;    Obj.showname=function () {       alert (this.name);    }         3, exit     return obj;} var p1=createperson (' Xiaomi ');p 1.showName ();

Differences from System objects:

var arr=new array ();//Generate a System array object

1, the system object is generated directly with new, and the factory is defined inside the function generated

2. Factory-defined function name the first is the lowercase start, and the system defines the uppercase start

Advantages and disadvantages of the factory model: Although the problem of creating similar objects has been resolved, the object recognition problem (i.e. how to know the type of an object) has not been resolved.

2. Constructors Create objects

When new calls a function, this is the object that is created, and the return value of the function is this (implicitly returned)

The function behind new is called the constructor

<1> constructor with parameters

function Createperson (name) {  this.name=name;  This.showname=function () {    alert (this.name);  }}    var p1=new createperson (' millet ');

<2> parameterless Constructors

function Createperson () {}    var p1=new createperson ();    P1.name= "Millet";    P1.showname=function () {     alert (p1.name);    }    P1.showname ();

Advantages and disadvantages of the constructor pattern:

1. Advantages: Creating a custom function means that its instance can be identified as a specific type in the future, where the constructor is better than the factory pattern

2. Cons: Each method must be recreated on each instance

3. Object literal method to create object

person={
Name: "Millet",
Age:23
};

4, using the prototype method

1. Prototype object: Whenever a new function is created, a prototype property is created for the function, which points to the prototype object of the function. By default, all prototype objects automatically get a constructor (constructor) property, which is a pointer to the function where the prototype property is located

2. You can use the isPrototypeOf () method to determine if this relationship exists between objects

function person () {}person.prototype.name= "millet"; Person.prototype.showname=function () {alert (this.name);} var p1=new person ();p 1.showName ();

Advantages and disadvantages of prototype mode:

1. Advantages: You can have all the object instances share the properties and methods that it contains

2, Disadvantage: The prototype is all the attributes are shared, but the instance is generally to have their own individual properties. Therefore, the prototype mode is seldom used alone.

5. Hybrid model

The constructor pattern defines the instance properties, while the prototype schema defines the methods and shared properties

function CReateperson (name) {  this.name=name;}  Create.prototype.showname=function () {    alert (this.name);  }    var p1=new createperson (' millet ');    P1.showname ();
   var p2=new createperson (' millet ');    P2.showname ();
alert (p1.showname==p2.showname);//true; reason: All under the prototype, there is only one copy in memory, the address is the same

Summarize:

function Constructor () {

this. Attribute;

}

Constructor. prototype. Method =function () {};

Var object 1=new Constructor ();

Object 1. Method ();

Prototype: To overwrite a common method or property under an object, so that a common method or property exists in memory (improves performance)

Prototype: Prototype: To write underneath the constructor

var  arr=[];arr.number=10; Array.prototype.number=20;alert (Arr.number);//10,
Reason: The common definition is more important than the prototype definition, the first will find their own, not the words and then follow the prototype chain to find out whether there is

If a property is to be placed under a prototype, it depends on whether the property is mutable, and if it is not mutable, it can be placed underneath the prototype, used for common properties, and variable to be placed underneath the constructor.

This is a pointing problem: it's easier to get into trouble with events or timers.

Second, the Packaging object

1, we put the system comes from the object, called the system object . Example: Array,date

2, Packaging objects : The basic types have their own corresponding packaging objects: String,number,boolean

var str= ' hello ';//Basic type: String type

Str.charat (0);//The base type finds the corresponding wrapper object type, and then wraps the object to give the base type all the properties and methods, and then wraps the object away.

str.number=10;//an object under the wrapper object, creates the property under the object, and then wraps the object away,

alert (str.number);//popup undefined; cause: An object is recreated under the wrapper object

Three, the prototype chain

Prototype chain: The connection between the instance object and the prototype, called the prototype chain

_proto_ (implicit connection)

The object type is the outermost layer of the prototype chain

  

Instance object first find itself below the properties and methods----not found in the prototype chain will find the object's prototype, and then see if there is a prototype to find the property or method, and then continue to find if it is found to return, or find the top level of the object is not really no

Iv. properties and methods in object-oriented

1. hasOwnProperty (): see if the properties and methods below the object itself

Only properties and methods that are defined by the object themselves return true, and return to False if the outgoing properties and methods are defined under prototype.

2. Constructor: View the constructor of an object

(can be used to detect a function type such as detecting whether an array)

Each prototype function automatically adds the constructor property (only one property is generated)

Some properties are not found when for in (the system comes with a property that is not found for the, and can be found by its own definition)

Avoid modifying the constructor property

function Aaa () {}//aaa.prototype.name= ' millet ';//aaa.prototype.age=6;//alert (a1.constructor);//AAA reason: Just add attributes to the prototype, is not re-assigned, the automatically added constructor property is still in the. aaa.prototype={//constructor: ' AAA ',//need to manually fix point to problem name: ' Xiaomi ', Age:6}var a1=new Aaa (); alert (a1.constructor);//object Cause: The prototype of the prototype is re-assigned, but there is no constructor

Note: Resetting the constructor property in this way causes its [Enumerable] attribute to be set to true, and the native constructor property is not enumerable by default. Can be modified by Object.defineproperty ().

3. instanceof: operator

Objects are related to the constructor on the prototype chain, and can be used as a type-wise but not the best solution, and the best solution is to use the ToString method to judge.

4. ToString (): Method on object, convert object to String

var arr=[];alert (arr.tostring==object.prototype.tostring);//false//reason: The system objects are all self-bringing ( For example, the array of ToString under Array.prototype), the object is written by the prototype chain to find Tostringfunction aaa () {}var a1=new aaa (); Alert ( a1.tostring==object.prototype.tostring);//true

1> using the ToString binary conversion

number.tostring (binary);

var Num=255;alert (num.tostring (+));//ff---Converted to 16, default does not write into decimal

2> uses ToString to make a type judgment:

In the case of cross-page, the above two cases will fail Var of=document.createelement (' iframe ');  Document.body.appendChild (' of '); var ifarray=windows.frames[0].  Array;//iframe array var arr=new ifarray (); alert (arr.constructor==array);//false alert (arr instanceof Array);//false alert (Object.prototype.toString.call (arr = = ' [object Array] ');//true

var Arr=[];alert (Object.prototype.toString.call (arr));//[object Array] var arr={};alert ( Object.prototype.toString.call (arr));//[object Object] var arr=new date;alert (Object.prototype.toString.call (arr)) ;//[object Date] var arr=new regexp;alert (Object.prototype.toString.call (arr));//[object RegExp]  

V. Inheritance

1, the way of succession:

1, copy inheritance : Universal type has new no new can be used

2. class inheritance : The new constructor---the way the constructor (class) inherits

3. prototype inheritance : No new object---using prototypes to implement object inheritance objects

 Property inheritance: Calling the constructor of the parent class call

 Method Inheritance: Copy inheritance in the form of in (JQ also inherits with copy)

var a = {name: ' Xiaomi '};            Copy inheritance function extend (obj1, obj2) {for (Var attr in obj2) {obj1[attr] = obj2[attr];            }}//prototype inherits Var B=cloneobj (a);            B.name= ' Little Joe ';            alert (a.name);            alert (b.name);                function Cloneobj (obj) {var f=function () {};                F.prototype=obj;            return new F ();        }//class inheritance function A () {//Parent class this.name= ' millet ';        } a.prototype.showname=function () {alert (this.name); } function B () {//Subclass A.call (this);//Properties and methods inherit separately}
B.prototype=new a ();//A sentence to implement inheritance, but there will be many problems, such as pointing to the problem, properties will affect each other
Class inheritance improvements: at least the following four sentences implement method inheritance, attributes need to be inherited separately
var f=function () {}; F.prototype=a.prototype; B.prototype=new F (); b.prototype.constructor=a;//fix points to problem var b1=new B (); B1.name= ' smile '; B1.showname ();

Object-oriented in JS (several ways to create objects)

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.