JS Object-oriented learning-object concept and object creation

Source: Internet
Author: User
Tags define object constructor contains functions modify return

I. Concept of objects

What is the object? An object is a collection of unordered attributes whose properties can include basic values, objects, or functions. That is, a set of unordered sets of name-value pairs.

The attributes of an object (not directly accessible), which means that the attribute contains two types of data properties and accessor properties.

1, the data attribute also contains

Configurable//Indicates whether delete can be deleted by Delete, default is true;
Enumerable//Indicates whether the property can be returned through a for-in loop, and the default is true;
Writable//Indicates whether the value of the property can be modified by default to TRUE;
Value//contains the data values for the property, which defaults to undefined

To modify the attributes of a default property, you must use the ECMAscript5 Object.defineproperty (the object of the property, the name of the property, the attribute attribute that needs to be modified). For example:


1, modify the default property characteristics,
var person = {};
Object.defineproperty (person, "name", {
Writable:false,
Value: "ABC"
});

alert (person.name); Abc
Person.name = "BCD";
alert (person.name); ABC instead of BCD, which is ignored in the strict mode, will be the error in strict mode

Once you have made such a setup, you cannot modify it again, or you will be able to make an error.


1, modify the default property characteristics,
var person = {};
Object.defineproperty (person, "name", {
Writable:false,
Value: "ABC"
});
Object.defineproperty (person, "name", {
Writable:true,
});

It is also important to note that when calling the Object.defineproperty () method, if you do not specify the (configurable,writable,enumerable) in the third argument, which is the property to modify, Then they all default to False


1, modify the default property characteristics,
var person = {};
Person.sex = "Nan";
Object.defineproperty (person, name, {//Here we modify the value of name, do not specify the property in the third argument, see the result
Writable:false,
Value: "ABC"
});

alert (person.name); Abc
Person.name = "BCD";
alert (person.name); ABC, not modifiable, default to False
Person.sex = "NV"; No call to DefineProperty, default or True
alert (person.sex); Nv



2, accessor properties

Configurable
Enumerable
Get//functions that are called when the property is read
Set//functions that are called when the property is written


2. Define accessor properties
var book = {
_year:2014,
Edition:1
}
Object.defineproperty (book, ' Year ', {//year is here to define accessor properties
Get:function () {
return this._year;
},
Set:function (value) {
This._year = value;
This.edition + = value-2004;
}
});
Book.year = 2005;
alert (book.edition); 2



When you need to define multiple properties, you can use Defineproperties (objects, attributes that need to be added);


3. Define multiple attributes
var books = {};

Object.defineproperties (Books, {
_year: {
value:2004
},
Edition: {
Value:1
},
Year: {
Get:function () {
return this._year;
},
Set:function (value) {
This._year = value;
This.edition + = value-2004;
}
}
});
Books.year = 2006;
alert (books._year); This is not the way to assign a value here, it returns 2004
var descriptor = object.getownpropertydescriptor (books, "_year");
Descriptor.value = 2006;
alert (Descriptor.value); 2006
Alert (typeof Descriptor.get);



These concepts seem to use less place, but to understand the JS object is very useful, the foundation, the foundation is always necessary, continue to learn ~



/*------------------------------------------------------------------------------------------------------------- --------------------------*/

/*==========================================================================*/

(I found that the equal sign line is not as good as the top short bar split line)



Second, create the object

A few days ago to see such a face test, JS create an object of several methods, only know that 3 kinds of writing, it is not clear what the principle is, today sorted out.

Factory mode
Constructor pattern
Prototype mode
Combining constructor patterns with prototype patterns



1. Factory mode


4. Factory mode
function Createperson (name) {
var obj = new Object ();
Obj.name = name;

Obj.show = function () {
alert (this.name);
}
return obj;
}
var person = Createperson ("ym");/no need to use new
Person.show ();



2, the constructor function pattern

The function name of the constructor begins with a capital letter, and the other functions are lowercase


5, the constructor function pattern
function person (name, sex) {
THIS.name = name;
var sex = sex; Private
This.show = function () {
alert (sex);
}
}
var person1 = new Person (' ym ', ' nan ');
alert (person1.name); Ym
alert (person1.sex); Undefined
Person1.show (); Nan

The difference from Factory mode:

Create object not shown
Assign directly to this object
No return statement

Problem with constructors:

When an object has more than one instance, all of the methods of these instances are different, because it is created once.


5, the constructor function pattern
function person (name, sex) {
THIS.name = name;
var sex = sex; Private
This.show = function () {
alert (sex);
}
}
var person1 = new Person (' ym ', ' nan ');
var person2 = new Person (' JH ', ' NV ');
Alert (person1 instanceof person); True
Alert (Person1.show = = person2.show); False



3. Prototype mode

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


6. Prototype mode
function Person2 () {}

Person2.prototype = {
Name: "YM",
Sex: ' Nan ',
Show:function () {
alert (this.name);
}
}

var a = new Person2 ();
var B = new Person2 ();
Alert (A.show = = b.show); True

About prototype, to its understanding is also very important, after a few days to learn to organize, read many times, feel or understand enough.

Prototype is a pointer to an object that contains the properties and methods shared by all instances, that is, the prototype object of the object instance that was created by calling the constructor.



Problem with prototype mode:

6. Prototype mode
function Person2 () {}

Person2.prototype = {
Name: "YM",
Sex: ' Nan ',
Love: [' A ', ' B '],
Show:function () {
alert (this.name);
}
}

var a = new Person2 ();
A.love.push (' C ');
var B = new Person2 ();
A.love.push (' d ');
Alert (A.show = = b.show);
alert (a.love); Abcd
alert (b.love); Abcd



4, combined use of prototype mode and constructor mode

We can see from the above example, the constructor pattern, the method that creates is different, all is the instance own own, while the prototype pattern defines the attribute and the method is to be shared, then combine to use really perfect.


6, Mixed Mode
function Perfect (name, sex) {
THIS.name = name;
This.sex = sex;
This.love = [' A ', ' B '];
}

Perfect.prototype = {
Constructor:perfect,
Show:function () {
alert (this.love);
}
}
var a = new Perfect (' A ', ' Nan ');
var B = new Perfect (' B ', ' NV ');
A.love.push (' C ');
B.love.push (' d ');
A.show (); Abc
B.show (); Abd

Finally finished, I also understand the original 3 ways to create objects is above the first 3 points, but it is best to use the 4th kind.



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.