JS Object-Oriented programming

Source: Internet
Author: User


Start learning JS object-oriented programming, online search of two articles, feel good writing. can refer to the reference.

First article: Turning from: http://www.cnblogs.com/gaojun/archive/2013/10/24/3386552.html

Object-oriented language has a flag, that is, the concept of the class, abstract instance objects of the public properties and methods, based on the class can create any number of instance objects, generally with encapsulation, inheritance, polymorphism characteristics. But the object in JS is different from the object in the pure object-oriented language, the ECMA standard defines the object in JS: The collection of unordered attributes, whose properties can contain basic values, objects, or functions. The object that can be simply understood as JS is a set of unordered values in which the property or method has a name that can be accessed based on the name (the value can be the base value/object/method). first, understand the object:

First: Object based

var person = new Object ();
Person.name = ' My name ';
Person.age = 18;
Person.getname = function () {
    return this.name;
}

Second: Object literal (a clearer look at the attributes and methods contained in the Lookup object)

var person = {
    Name: ' My Name ',
    Age:18,
    Getname:function () {
        return this.name;
    }
}

JS objects can use the '. ' Operator dynamically expands its properties, you can delete the property by using the ' delete ' operator or by setting the property value to ' undefined '. As follows:

person.newatt= ' new Attr '//Add Property
alert (Person.newatt);//new Attr
Delete Person.age;
alert (person.age);//undefined (delete attribute after value is undefined);
Second, object attribute type

ECMA-262 5th Edition Defines the characteristics of JS object properties (for JS engine, external can not directly access). There are two properties in ECMAScript: Data properties and Accessor properties 1, Data properties:

A Data property is a location that contains a data value that can be read or written to in a value that has 4 attributes for its behavior:

[[Configurable]]: Indicates whether the delete operator can be used to delete to redefine it or whether it can be modified to an accessor property. The default is true;

[[Enumberable]]: Indicates whether the property can be returned by a for-in loop. Default true;

[[writable]]: Indicates whether the value of the property can be modified. Default true;

[[value]]: The data value that contains the property. Both read/write is the value. The default is undefined; the name attribute, whose value is ' My name ', is defined in the instance object person above, and the value is modified in this position anyway

To modify the default feature of an object property (the default is True), call the Object.defineproperty () method, which receives three parameters: the object of the property, the property name, and a descriptor object (must be: configurable, enumberable, Writable and value, you can set one or more values.

as follows : (Browser support: ie9+, Firefox 4+, Chrome, safari5+)

var person = {};
Object.defineproperty (person, ' name ', {
    Configurable:false,
    Writable:false,
    Value: ' Jack '
});
alert (person.name);//jack
Delete Person.name;
Person.name = ' Lily ';
alert (person.name);//jack

As you can see, the value of delete and reset Person.name is not in effect because the call to the DefineProperty function modifies the characteristics of the object's properties; It is noteworthy that once the configurable is set to False, You can no longer use DefineProperty to modify it to true (an error can be performed: Can ' t redefine non-configurable property); 2, accessor properties:

It consists primarily of a pair of getter and setter functions that invoke the getter to return a valid value when the accessor property is read, when the accessor property is written, the setter is invoked, the new value is written, and the property has the following 4 characteristics:

[[Configurable]]: Whether the redefined attribute can be deleted by the delete operator;

[[Numberable]]: Whether the property can be found by for-in loops;

[[get]]: Called when reading properties, default: undefined;

[[Set]]: Called when writing properties, default: undefined;

Accessor properties cannot be directly defined and must be defined using DefineProperty (), as follows:

var person = {
    _age:18
};
Object.defineproperty (person, ' isadult ', {
    Get:function () {
        if (this._age >= 18) {
            return true;
        } else {
            return false;
        }
    }
});
Alert (person.isadult? ') Adult ': ' Minors ');/adult

It can be seen from the above that getter and setter functions are not necessary when defining accessor properties, and the configurable and writable characteristics of attributes cannot be specified when getter and setter are defined;

In addition, ECMA-262 (5) also provides a object.defineproperties () method that can be used to define attributes for multiple properties at once:

var person = {};
Object.defineproperties (person,{
    _age:{
        Value:19
    },
    isadult:{
        Get:function () {
            if (this._age >= 18) {
                return true;
            } else {
                return false;
            }
        }
    }
});
Alert (person.isadult? ') Adult ': ' Minors ');/adult

The code above uses the Object.defineproperties () method to define the attributes of both _age and ISAUDLT two properties

In addition, you can use the Object.getownpropertydescriptor () method to get the attributes of a given property:

var descriptor = Object.getownpropertydescriptor (person, ' _age ');
alert (descriptor.value);//19

For data attributes, you can obtain: configurable,enumberable,writable and value;

For accessor properties, you can get: Configurable,enumberable,get and set three, creating objects

objects can be created with the object constructor or object literal, but the disadvantage is that when multiple objects are created, there is a lot of duplication of code, so here's how to create the object that resolves the problem 1, Factory mode

function Createperson (name, age, Job) {
    var o = new Object ();
    O.name = name;
    O.age = age;
    O.job = job;
    O.getname = function () {
        return this.name;
    }
    Return o;//Returns the generated object instance using
}
var person = Createperson (' Jack ', ' SoftWare Engineer ');

The creation of objects is delivered to a factory method, which can pass parameters, but the main disadvantage is that the object type is not recognized because the object is created using the native constructor of object. 2, the constructor function pattern

function Person (name,age,job) {
    THIS.name = name;
    This.age = age;
    This.job = job;
    This.getname = function () {
        return this.name;
    }
}

var person1 = new Person (' Jack ', ' SoftWare Engineer ');

var person2 = new Person (' Liye ', N, ' mechanical Engineer ');

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.