Js006-Object-Oriented programming

Source: Internet
Author: User

js006- Object-Oriented programming

The object-oriented (Object-oriented,oo) language has a sign that they all have the concept of a class. Through a class, you can create multiple objects with the same properties and methods.

ECMA-262 defines an object as a collection of unordered properties whose properties can contain basic values, objects, or functions. (An object is a set of values that do not have a specific order). Each method or property of an object has a specific name, and each name is mapped to a specific value. objects can be imagined as a hash table, a set of name-value pairs, which can be data or functions.

Each object is created based on a reference type.

6.1 Understanding Objects

The simplest thing to create a custom object is to create an instance of an object, and then add properties and methods to it.

var person = new Object ();

Person.name = "Meimei";

Person.age = 18;

Person.job = "Software Enginer";

Person.sayname = function () {

alert (this.name);

};

Created an object named person, added three properties and assigned values, and a method sayname for displaying this.name

6.1.1 Property Type

There are two types of properties in ECMAScript: Data properties and accessor properties

Data properties: A location that contains a data value that can be read and written to. Four attributes describe the behavior of a data property

[[Configurable]]

Indicates whether the property can be redefined by deleting the property through the delete, whether the attribute is modified, or whether the property can be modified as an accessor property. The default value is: True

[[Enumerable]]

Indicates whether the property can be returned through a for-in loop. The default value is: True

[[Writable]]

Indicates whether the value of the property can be modified. The default value is: True

[[Value]]

Contains the data value of this property, read the value of the property, read from this position, when writing the property value, save the new value to this location, the default value of this attribute is undefined

The default attribute to modify properties must use the Object.defineroperty () method. The method receives three parameters: the object where the property resides, the name of the property, and a descriptor object. The properties of the Descriptor object must be: Configurable, Enumerable, writable, value, set one or more of these values, and you can modify their default values.

Accessor Properties : The Accessor property does not contain a data value; It contains a pair of getter and setter functions (neither of these functions are required)

Getter function

Called when the accessor property is read, returns a valid value

Setter functions

Write accessor property is called, passing in the new value

Accessor properties have the following four attributes:

[[Configurable]]

Indicates whether the property can be redefined by deleting the property through the delete, whether the attribute is modified, or whether the property can be modified as an accessor property. The default value is: True

[[Enumerable]]

Indicates whether the property can be returned through a for-in loop. The default value is: True

[[Get]]

The function that is called when the accessor property is read, the default value is: Undefined

[[Set]]

The write accessor property is the function that is called, and the default value is: Undefined

Accessor properties cannot be defined directly and must be defined using Object.defineproperty ():

var book = {

_YEAR:2015,

_edition:1

};

Object.defineproperty (book, ' Year ', {

Get:function () {

if (NewValue > 2015) {

This.year = newvalue;

This.edition + = newValue-2015;

}

}

});

Book.year = 2016;

alert (book.edition); 2

A book object is created and a default property is defined.

_ (Add an underscore) represents a property that can be accessed only through an object.

6.1.2 Define multiple properties

Multiple properties can be defined vaguely by the object.defineproperties () method. The method receives two parameters, the first: object to add and modify its properties, and the properties of the second object correspond to the property one by one to be added or modified in the first object.

Such as

var book ={};

Object.defineproperties (book,{

_year:{

Writable:true,

value:2015

},

edition:{

Value:1

},

year:{

Get.function () {

return this._year;

},

Set:function (NewValue) {

if (NewValue > 2015) {

This.year = newvalue;

This.edition + = newValue-2015;

}

}

}

});

Defines two data attributes for book exclusive _year and edition and an accessor property (year). The final object is the same as the one defined in the previous section, except that the properties are created at the same time.

6.1.3 Properties of the Read attribute

var book ={};

Object.defineproperties (book,{

_year:{

value:2015;

},

edition:{

Value:1

},

year:{

Get:function (NewValue) {

if (NewValue > 2015) {

This._year = newvalue;

This.edition + = newValue-2015;

}

}

}

});

var descriptor = object.getownpropertydescriptor (book, "_year");

alert (Descriptor.value); 2015

alert (descriptor.configurable); False

Using the Object.getownpropertydescriptor () method, you can get a descriptor for a given property that receives two parameters: the object where the property resides and the name of the property whose descriptor you want to read. The return value is an object, and if it is an accessor property, the object's properties are: Configurable, Enumerable, Get, Set

If it is a data attribute, the properties of this object are: Configurable, Enumerable, writable, Value

6.2 Creating Objects

A variant of the factory pattern is to solve the disadvantage of creating a single object with the object constructor or the literal: using the same pretext to create many objects produces a lot of duplicate code.

6.1.1 Factory mode

This pattern abstracts the process of creating concrete objects. Because a class cannot be created in ECMAScript, a function is used to encapsulate the details of the object created by a particular interface.

Example:

Function Createperson (name, age, Job) {

        var o = new Object ();

       o.name = name;

       o.age = age;

       o.job = job;

       o.sayname = function () {

               alert (this.name);

      };

       return o;

}

var person1 = Createperson ("Meimei", "Teacher");

var person2 = Createperson ("Lal-alice", "Software Enginer");

Multiple calls to Createperson () function

 

 

Run and test in console:

Console.log (Person2);

Object {name: "Lal-alice", age:18, Job: "Software Enginer"}

 

But engineering mode does not solve the problem of object recognition (how to know the type of an object)

6.2.2 Constructor Model

Native constructors, such as object and array, will automatically appear in the execution environment at run time. You can create custom constructors to define properties and methods for custom object types. For example, you can use the constructor pattern to rewrite the preceding example as follows:

function person (name, age, Job) {

THIS.name = name;

This.age = age;

This.job = job;

O.sayname = function () {

alert (this.name);

};

}

var person1 = new Person ("Meimei", "Teacher");

var person2 = new Person ("Lal", "Software Enginer");

Person () replaces the Createperson () function. It is relatively different: the person ()

1, not explicitly create objects;

2, directly assigns the attribute and the method to this object;

3, no return statement.

The first letter of the constructor (which can be used as a constructor), as long as it is called by the new operator, is generally uppercase. A non-constructor should start with a lowercase letter. This is primarily to distinguish it from other functions in ECMAScript, because the constructor itself is Korean, but it can be used to create an object:

To create a new person instance, you must use the new operator. Calling the constructor in this way goes through the following 4 steps:

Create a new object

Assigning the scope of a constructor to a new object

Execute the code in the constructor (Add new property)

return new Object

Person1 and Person2 Each save a different instance of person. They all have a property: constructor (constructor), which points to person. This property is used to identify the object type. For object type detection, it is best to use: instanceof operator.

1, the constructor as a function.

The previous person () function can be invoked in any of the following ways

Use as a constructor function

var person2 = new Person ("Lal-alice", "Software Enginer");

Person.sayname ();//"Lal-alice"

Called as a normal function

Person ("Lal-alice", "Software Enginer");

Window.sayname ();//"Lal-alice"

Called in the scope of another object

var o = new Object ();

Person.call (O, "Lal-alice", "Software Enginer");

O.sayname ();//"Lal-alice"

2, the problem of the constructor function

Major problem: Each method is recreated on each instance.

6.2.3 prototype Mode

Each function we create has a prototype property, which is a pointer to an object.

(This part of the note, then fill up, first read carefully.) 2016/1/20 15:41)

6.2.4 combining the constructor pattern with the prototype pattern

The most common way to create a custom type is by combining the constructor pattern with the prototype pattern. Constructor patterns are used to define instance properties, which are used to define methods and shared properties. The result: each instance has its own copy of the strength attribute, while sharing a reference to the method, maximizing memory savings.

The following code:

function person (name, age, Job) {

THIS.name = name;

This.age = age;

This.job = job;

This.fiiends = ["Shelby", "Court"];

}

Person.prototype = {

Constructor:person;

Sayname:function () {

alert (this.name);

}

}

var person1 = new Person ("Meimei", "Teacher");

var person2 = new Person ("Lal", "Software Enginer");

Person1.fiiends.push ("Van");

alert (person1.fiiends); "Shelby,court,van"

alert (person2.fiiends); "Shelby,court"

Alert (Person1.fiiends = = person2.fiiends); False

Alert (Person1.sayname = = Person2.sayname); True

The instance properties are defined in the constructor, and the properties constructor and Method Sayname () shared by all instances are defined in the prototype. and modified the person1.fiiends, does not affect the Person2.fiiends

6.2.5 Dynamic Prototyping Mode

You can determine whether a prototype needs to be initialized by checking that a method that should exist is valid. For example:

function person (name, age, Job) {

Property

THIS.name = name;

This.age = age;

This.job = job;

Method

if (typeof this.sayname! = "function") {

Person.prototype.sayName = function () {

alert (this.name);

}

};

}

var friend = new Person ("Lal-alice", "Software Enginer");

Friend.sayname ();

Bold code is added to the prototype only if the Sayname () method does not exist, and this code is called only when the initial constructor is in progress.

6.2.6 Parasitic Constructors

The parasitic (parasitic) mode can be used in cases where the previous centralized mode is not applicable. The basic idea is to create a function that encapsulates the code that creates the object, and then returns the newly created object.

6.2.7 Parasitic Constructors

The so-called secure object refers to the absence of a public property, and its method does not refer to the object of this.

(Copyright notice: This blog for http://www.cnblogs.com/lal-fighting/original published, without permission, not reproduced or copied!!!) )

6.3 Inheritance

There are generally two ways of inheriting: an excuse to inherit and implement inheritance.

ECMAScript only supports implementation of inheritance, and implementation of inheritance is achieved primarily through the prototype chain.

6.3.1 prototype chain

Basic idea: Use a prototype to have a reference type inherit the properties and methods of another reference type.

There is a basic pattern for implementing the prototype chain, which is roughly the following code:

Prototype chain

function Suppertype () {

This.property = true;

SupperType.property.getSuperValue = function () {

return this.property;

};

}

Function subtype () {

This.subproperty = false;

}

Inherited the supertype.

Subtype.propertype = new Suppertype ();

SubType.propertype.getSuperValue = function () {

return this.subproperty;

};

var instance = new Suppertype ();

Alert (Instance.getsupervalue ()); True

Two types are defined: Supertype subtype. Each type has one property and one method.

(not completed, after the note is mended)

1, don't forget the default prototype

2. Determine the relationship between prototypes and instances

3. Carefully define the method

6.3.2 borrowing Constructors

Also known as forged objects or classic inheritance.

Basic idea: Call a super-type constructor inside a subtype constructor. Constructors can also be executed on newly created objects by using the Apply () and Call () methods (in the future)

1, pass the parameter: compared to the prototype chain, borrowing a constructor has a great advantage, you can pass the parameters to the copy type constructor in the sub-type constructor function.

2. The problem of borrowing constructors: there is no way to avoid problems with constructor patterns-methods are defined in constructors, so functions cannot be reused. Also, in the case of super-type prototypes, the methods defined are not visible to the subtypes. Result all types can only use constructor mode

6.3.3 Combining Inheritance (most commonly used inheritance)

Also known as pseudo-classical inheritance, refers to the prototype chain and borrowed the technology of the constructor into a piece, so as to play the two long of a succession mode.

Idea: Using the prototype chain to implement the inheritance of the prototype properties and methods, and by borrowing the constructor to implement the inheritance of the instance properties.

Combined inheritance avoids the defects of prototype chains and borrowed constructors, and incorporates their advantages, becoming the most common inheritance in JavaScript.

(Notes not updated)

6.3.4 prototype Inheritance

6.3.5 Parasitic Inheritance

6.3.6 Parasitic combined inheritance

Copyright notice: This blog for http://www.cnblogs.com/lal-fighting/original published, without permission, not reproduced or copied!!!

Js006-Object-Oriented programming

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.