JavaScript Object Oriented (1)--talking about object __java

Source: Internet
Author: User
Tags inheritance object object hasownproperty

Many students have ignored the fact that JavaScript can also do object-oriented programming for quite a long time. On the one hand, the various page interactions that we have implemented in the introductory phase are very logical to be solved with procedural programming, and we just need to write a few methods and then bind the events to the DOM nodes in the page to complete. In particular, such as my first C + + such language did not study well, a major language is JavaScript students, the process of programming thinking seems more deep-rooted. On the other hand, even for programmers in languages such as Java and C + +, JavaScript is a heterogeneous object: There is no concept of class in JavaScript (not in ES5 and previous versions, ES6 will be introduced separately), The prototype inheritance pattern is also different from the traditional object-oriented language, and the weak type of JavaScript makes many people mad. Of course, this flexibility can bring a lot of benefits when you're familiar with it. In short, encapsulation, inheritance, polymorphism, aggregation of these object-oriented basic features JavaScript has its own implementation, the knowledge of learning from the entry level JS programmer to step in the way.

JavaScript Object Oriented (1)--talking about objects

JavaScript Object Oriented (2)--talking about functions (functions, objects, closures)

JavaScript object-oriented (3)--prototype and inheritance model based on constructors (prototype chain)

JavaScript object-oriented (4)-Best inheritance mode (deep copy, multiple inheritance, constructor borrowing, combined parasitic inheritance)



For a long time did not update the blog, the direction of the period has changed a lot, and now in preparation for studying abroad, technical learning is much less. This period of time has been trying to change the direction of the process of thinking, the issue of the problem sent to the studio to send the old just the past, each level of students have their own problems, perhaps my thinking process can bring inspiration. Of course, if I'm wrong in the future, these thoughts can be used as lessons. haha.

There is no doubt that JavaScript is an object-oriented programming language, and its object-oriented implementation mechanism is so special. Recently want to put this whole piece of knowledge, first from some of the language characteristics of JavaScript, talk about variables, talk about objects, talk about functions, talk about JavaScript object-oriented implementation.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~


To talk about objects in JavaScript, we want to start with the data type of JavaScript. In JavaScript, except for strings, numbers, true, false, NULL, and undefined, all values are objects, and objects are first-class citizens in JavaScript. Object itself, is a series of attributes of the unordered set, that is, a set of key-value pairs, such a data structure in other places is called "hash", "dictionary", "associative array" and so on ~ where the key is a string, and the value can be any data type in JS.

JS objects are reference types, are variable, and also dynamic. We assign the object to another variable and do not create a new copy of the object, just a reference to the object, and the object is mutable, and all variables referencing the object change after the statement modifies the object's contents. JS and the dynamic nature of the object allows us to operate on attributes, add, delete, etc. can be carried out at any time. This feature is very important in the later object-oriented implementation, in the traditional object-oriented language we must design the class in advance, the method and behavior in advance design, in JS, we can use the object directly to expand it, is to take advantage of its dynamic. Before discussing objects from several aspects, there are some concepts to know about objects and attributes:

Object attributes: In addition to attributes, some of the attributes that an object has, including:

object's prototype: Point to another object, equivalent to the parent object.

Object class: A string that identifies the type of the object.

Object that indicates whether a new attribute can be added to the object.

Object classification: A total of three types of JavaScript objects are based on the source of the object:

Built-in objects: objects and classes defined by the ECMAScript specification, including arrays, functions, dates, regular expressions, errors, and so on, enter the domain of the JavaScript language core.

Host object: defined by the hosting environment embedded by the JavaScript interpreter. For example, the document object is defined by the browser. (Remember when you first contacted Nodejs to use REPL, you hit a alert~ alert is provided by a browser-defined window object that does not exist in the NODEJS environment.) )

Custom object: An object created by a running JavaScript statement

Attribute attribute: In addition to the name and value, there are several attribute values associated with each attribute: writable, enumerable, configurable. They determine whether the property is writable, whether it can be returned through the for/in loop, and why it is deleted or modified.

Attribute categories: Own and inherited properties. A free property is a property that is defined directly in an object, whereas an inherited property is a property defined in the object's prototype object.


three ways to create objects

1, through the object directly to create: Curly braces is an object, key-values separated by a colon, key-values separated by commas. Well, yes, that's the JavaScript Object Notation (JSON).

var object = {
	"name": "Zhuwq",
	"age": "
	Callhim": function () {
		//call me
	},
	"Girlfriend": {
		' name ': Undefined,
		' age ': Undefined
	}
}

2. Create an object from the New keyword: As with other object-oriented languages, you can use the New keyword to invoke a constructor to initialize an object. JavaScript built-in objects are built with built-in constructors:

The var object = new Object (),
	array = new Array (),
	date = new Date (),
	regExp = new RegExp ();

It is more important to use a custom constructor to initialize the new object, which is detailed later.

3, using the Object.create () method: For this object creation method, the concept of the prototype is very important:

The Object.create () method, which is provided by the ES5, can create a new object by passing the prototype object (the prototype will be discussed separately later) as a parameter:

var obj = {"name": "obj"};
var O1 = object.create (obj);
OBJ.A;  "obj"
var O2 = object.create (null);             Create a new object without a prototype
var O3 = object.create (Object.prorotype);//Create a plain empty object with var O3 = {}; and var O3 = The new object ();

second, the operation of the property1. Access and modification of properties: You can access the properties of an object through the dots (.) and brackets ([]) operators:
var obj = {"name": "obj"};
Obj.name;   "Obj"
obj["name"];//"Obj"
For a point, the right side must be a simple identifier named with a property, and the square brackets must be an expression that returns a string or can be converted to a string. This makes it possible to do more flexible work in some cases by using the square brackets, which are similar to an associative array of access methods:
var addr = {};
for (var i = 0;i < 5;i++) {
	addr["name" +i] = i;
}
Addr {name0:0, name1:1, Name2:2, Name3:3, Name4:4}
In many scenarios where property names cannot be predicted, the program can only be completed using array notation. You can also use for/in loops to traverse object properties:
var object = {
	"name": "Zhuwq",
	"age": "
	Girlfriend": {
		"name": Undefined, "Age
		": Undefined
  }
}
var message = ';
For (Pro in object) {message
	+ + Pro + ":" + Object[pro] + ",";
}
Message Name:zhuwq,age:21,girlfriend:[object Object],
2. Add property: When accessing a property, assigning a value directly to a nonexistent property adds the property directly:
var obj; = {};
OBJ.A = "a";
Obj["B"] = "B";
Obj {"A": "A", "B": "B"}
3, the deletion of the property: directly using the delete operator can
var obj = {"A": "A", "B": "B"};
Delete obj.a; True
obj;//{"B": "B"}
4. Accessor properties: The object properties we normally use are called data attributes, and accessor properties are added from the ES5. It allows an object's property value to be overridden by one or two methods: The Setter method is invoked when the program sets the value of an accessor property, and the Getter method is invoked when the program queries the value of an accessor property. Similarly, you can add only getter methods or add setter methods to make this property a read-only or write-only property. When defining accessor methods, instead of using a GET or set keyword to define a method with the same name as the property name, the function body and the property name do not need to be separated by colons, but a comma is still required between the body of a function and the next: Functon keyword.
var rectangle = {
    width:1.0,
    height:2.0,
    name:undefined, get area
    () {return
        This.width * This.height
    },
    set Namevalue (newName) {
        this.name = newName;
    }, Get
    namevalue () {return
        " This object ' s name is ' + this.name;
    }
}
Rectangle.area;  2
rectangle.namevalue = "Zhuwq";
Rectangle.namevalue;  This object ' s name is ZHUWQ
When using accessor properties, be aware that accessor properties and data properties cannot have the same name, which will report rangeerror errors.  When it comes to memory properties, it's possible to use the accessor properties as a way to manipulate the data properties of the same name, and you need to be aware of them. Similarly, accessor properties can be inherited.

iii. Characteristics of attributesAs described in the beginning of the article, the properties in a JavaScript object, in addition to their name and value, have three attributes that identify whether they are writable, enumerable, and configurable. In the ES3 era, these features cannot be modified, and all properties created by the program are writable and enumerable configurable. Starting with ES5, JavaScript contains the API for configuring attribute attributes. Attributes of data properties include value, writable, enumerable, and configurable, while the attributes of accessor properties include read, write, enumerable, and configurable.
1, detection properties: At some point we need to detect whether there is a property in the object, and the property is its own property or inherited properties. Here are a few ways:
Build Object
var object1 = {
    x:1
}
var object2 = object.create (object1);
OBJECT2.Y = 2;

Detection Method 1:  use the in operator to distinguish between free and inherited properties
"X" in Object2;//True
"Y" in object2;//True
"Z" in Object2;//FALSE
  //detection Method 2:  use the hasOwnProperty () method to detect whether it is own property
Object2.hasownproperty ("x");//False inherits from Object1
Object2.hasownproperty ("Y"); True
object2.hasownproperty ("z");//False No this property

//Detection Method 3:  Use the propertyIsEnumerable () method to detect whether an enumerable owned property
object2.propertyisenumerable ("x");        False inherits from Object1
object2.propertyisenumerable ("Y");        True
object2.propertyisenumerable ("z");        False without this attribute
object2.propertyisenumerable ("toString");//false not enumerable
There is also a case for distinction: When an object does not have this property or if the property value is undefined, accessing the property returns undefined. This is the time to use the in operator and the!== operator to differentiate between these two situations on demand.

2, property characteristics of the query: ES5 defines a property descriptor object, by passing the object and the property name as a parameter to the Object.getownpropertydescriptor () method can get the object of the property descriptor. It should be noted that this can only get the property descriptor property, to query the attributes of inherited properties, you need to use object.getprototypeof () and other methods to obtain the prototype object and then query. :
var rectangle = {
    width:1.0,
    set Namevalue (newName) {
        this.name = newName;
    }, Get
    namevalue () { Return
        "This object ' s name is" + this.name;
    }
}
Object.getownpropertydescriptor (Rectangle, "width"); {value:1, writable:true, Enumerable:true, configurable:true}
object.getownpropertydescriptor (Rectangle, " Namevalue ");/{get: [Function:get Namevalue], set: [Function:set namevalue], enumerable:true, Configurable:true}
  object.getownpropertydescriptor (Rectangle, "AAA"); Undefined
object.getownpropertydescriptor (Rectangle, "toString");//undefined
3. Creation and modification of attribute attributes: there are Object.defineproperty () and Object.defineproperties () two methods, which are used to create or modify individual property attributes and multiple attribute attributes:
Configure the property attribute of an individual property
var obj = {} By passing the object, property, property descriptor object to the Object.defineproperty () object;
Object.defineproperty (obj, "B", {
    value:1,
    writable:true,
    enumerable:true,
    configurable:true
});
OBJ.B; 1
object.defineproperty (obj, "B", {
    value:1,
    writable:false,
    enumerable:true,
    Configurable:true
});
OBJ.B = 2; 
OBJ.B; 1   Only the writable configuration is shown here
Configure the property attribute of multiple properties
var obj = {} By passing the collection object of the object, property, and its descriptor to the object.defineproperties () object;
Object.defineproperties (obj,{
    B: {value:1,writable:false, enumerable:true, configurable:true},
    c: {get: function () {return ' Get C '}, Set:undefined,enumerable:true, configurable:true}
});
OBJ.B = 2; 
OBJ.B; 1
obj.c//Get C
Of course, the success of both operations is associated with the extensibility of the object, the configurable nature of the property, and the writable nature. If the operation fails, a type error exception is thrown.

Four, three characteristics of the object1, prototype attributes: Prototype and prototype chain is the core of JavaScript-oriented object, will be a separate story. The object's prototype property is set when the object is created, and there are three prototypes set up according to three ways to create the object.                In ES5, we can query the prototype of an object by the Object.getpropertyof () method. 2. Class attribute: Class property is a string that identifies an object type, and there is no way to modify this property in ES5. We can get the object's class attribute by calling the object's ToString method. Because many object-inherited ToString methods are overridden, here is a method provided in the JavaScript Authority Guide, where various data types can be passed in directly:
function Classof (obj) {
    if (obj = = null) return "NULL";
    if (obj = = undefined) return "undefined";
    return Object.prototype.toString.call (obj). Slice (8,-1);
}
3. Scalability: The extensibility of an object determines whether new attributes can be added to an object. All of the built-in objects and custom objects in JavaScript are extensible. There are some ways to turn an object into an extensible one, and it should be noted that once you become an extensible object, you cannot change it back. To close the object, can avoid the outside interference. There are three ways to lock objects from varying degrees, and here is an incremental introduction:
Query whether an object can extend
var obj = {} through the object.esextensible () method;
Object.esextensible (obj); True

//Convert an object to an
object.preventextensions (obj) by object.preventextensions () method;
Object.esextensible (obj); False

var obj = {a:1};
The Object.seal () method makes the object extensible and makes all its own properties not configurable
//can use the object.issealed () method to determine if
object.issealed (obj) has been closed; False
object.seal (obj);
object.issealed (obj); True
object.esextensible (obj);//false
object.defineproperty (obj, "B", {
    value:1,
    writable: False,
    enumerable:true,
    configurable:true
});//Typeerror:cannot define PROPERTY:B, object is not exte Nsible.

var obj = {a:1};
The Object.freeze () method converts an object to not extensible, sets all its own properties to be not configurable, sets all data properties to read-only
//can use the Object.isfrozen () method to determine whether it is closed
Object.isfrozen (obj); False
Object.freeze (obj);
Object.isfrozen (obj); True
object.esextensible (obj);//false
object.defineproperty (obj, "B", {
    value:1,
    writable: False,
    enumerable:true,
    configurable:true
});  Typeerror:cannot define PROPERTY:B, object is not extensible.
B.A = 2;
B.A; 1


v. Method of ObjectAll JavaScript objects inherit properties from Object.prototype, most of which are methods. Some of the above have been mentioned: hasOwnProperty (), propertuisenumerable (), isprototypeof (), Object.create (), object.getprototypeof () and so on. The same methods that are inherited from Object.prototype, such as ToString (), tolocalstring,valueof (), and so on, are very useful.  But many objects override these methods, for example, if you call your own ToString method on an Array object, you get a list of array elements, each of which converts to a string, and if you call the original ToString method, you get only the [array array] string. As for these methods, we do not repeat them here.





Related Article

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.