JavaScript Object-oriented essentials (i)

Source: Internet
Author: User
Tags object object types of functions hasownproperty

Data type

In JavaScript, data types fall into two categories:

Original type

Save some simple data, such as true,5. JavaScript has a total of 5 original types:

    • Boolean: Boolean with a value of true or False
    • Number: Numeric value for any integral type floating point value
    • String: A single character or consecutive character that is enclosed by single or double quotation marks (JavaScript is not distinguished by character type)
    • Null: null type, with only one value: nulll
    • Undefined: Not defined, it has only one value: undefined
var name = "Pomy"; var blog = "http://www.ido321.com"; var =N; alert (typeof//"string"alert (typeof//  "Number"

The value of the primitive type is stored directly in the variable and can be detected with TypeOf. However, typeof Null is detected by returning an object instead of returning null:

// Eject NOT NULL if (typeofnull) {    alert ("not NULL");   } Else {    alert ("null");}

Therefore, when NULL is detected, it is best to use all equals (= = =), which also avoids coercion of type conversions:

Console.log ("+" = = =);  // falseConsole.log ("+" =);  // true null);  // true null);  // false

For string, numeric, or Boolean values, there are methods that come from the corresponding original package type: string, number, and Boolean. The original package type is automatically created.

var name = "Pomy"; var char = Name.charat (0); Console.log (char);  // "P"

Things that happen in the JavaScript engine:

var name = "Pomy"; var New String (name); var char = Temp.charat (0null; Console.log (char);  // "P"

A reference to a string object is destroyed immediately after it is exhausted, so a property cannot be added to the string, and false is returned when instanceof detects the corresponding type:

var name = "Pomy"= +; console.log (name.age);    // undefined instanceof String);  // false

Reference type

Saved as an object, essentially a reference to a memory location, so the object is not saved in the variable. In addition to custom objects, JavaScript provides a built-in type of 6:

    • Array: An ordered list of arrays of type, indexed by number, of a set of values
    • Date: Day and Time type
    • Error: Run-time error type
    • function: Types of functions
    • Object: Universal Object Type
    • REGEXP: Regular Expression type

You can instantiate each object with new, or create an object in literal form:

var New Object; var own = {            name:"pomy",            Blog:"http://www.ido321.com",            "My Age": 22         };console.log (own.blog);     // Access attribute console.log (own["My Age"null;  // de-referencing

Obj does not contain an object instance, but rather a pointer (or reference) to the location of the actual object in memory. Because typeof returns object for all reference types of non-functions, it is necessary to use instanceof to detect reference types.

Function

In JavaScript, a function is an object. The defining feature of making a function different from other objects is that the function has an internal property called [[Call]]. Internal properties cannot be accessed through code, but rather define the behavior of code execution.

Create form

1, function declaration: Using the Functions keyword, will be promoted to the context

2. Function expression: cannot be promoted

3. Instantiation of function built-in type

Sayhi ();    // function Promotion function Sayhi () {    console.log ("Hello");} // other equivalent equivalent methods /* var sayhi = function () {     console.log ("Hello");} var sayhi = new Function ("Console.log (\" hello\ ");"); */

Parameters

Another unique characteristic of JavaScript functions is the ability to pass any number of arguments to a function. The function arguments are stored in the arguments class array object, which automatically exists in the function and can be referenced by a numeric index, but it is not an array instance:

Alert (Array.isarray (arguments));   // false

The class Array object arguments holds the arguments for the function, but does not omit the parameters. Thus, Arguments.length returns the length of the argument list, Arguments.callee.length returns the length of the parameter list.

function Ref (value) {    return  value;} Console.log (ref ("HI")), Console.log (ref ("HI"),Console.log (  ref.length) ; // 1

This in the function

For a question about this, refer to this article: this in JavaScript.

JavaScript provides three ways to change the point of this: call, apply, and bind. The first parameter of the three function is the value that specifies this, and the other parameters are passed as arguments to the function.

Object

An object is a reference type that is commonly used to create objects in two ways: the object constructor and the object literal form:

var per1 = {    name:"pomy",    Blog:"http://www.ido321.com"}; var New  = "code-farmers who do not write codes";

Property manipulation

In JavaScript, you can add properties to an object at any time:

Per1.age = 0function() {    alert (this. name);   // "Pomy"}

Thus, when detecting the existence of object properties, one common mistake is:

// The result is false if (per1.age) {    alert (true)}else{    alert (false  );}

The per1.age is present, but its value is 0, so the IF condition cannot be satisfied. If the value in the If judgment is an object, a non-empty string, a non-0 number, or true, the judgment evaluates to true, whereas a null, undefined, 0, False, Nan, or empty string evaluates to False.

Thus, there are two other ways to detect if a property exists: in and hasOwnProperty (), which detects both the prototype attribute and its own (instance) attribute, which detects only its own (instance) attributes.

 in per1);  // trueconsole.log (Per1.hasownproperty ("Age"));  // true  in per1);  // trueconsole.log (Per1.hasownproperty ("toString"));  // false

Object Per1 does not define ToString, which inherits from Object.prototype, so in and hasownproperty () differences occur when the property is detected. If you just want to determine whether an object property is a prototype, you can use the following methods:

function Isprototypeproperty (obj,name) {    return in obj &&!  Obj.hasownproperty (name);}

To delete a property, use the delete operator to delete the own property, and you cannot delete the prototype property.

function () {    console.log ("Per1 object");}; Console.log (Per1.hasownproperty ("toString"));   // trueper1.tostring ();   // "Per1 Object" Delete Per1.tostring;console.log (Per1.hasownproperty ("toString"));   // falseConsole.log (per1.tostring ());  // [Object Object]

Sometimes you need to enumerate the enumerable properties of an object, and there are two ways: For-in Loop and Object.keys (), which will still traverse the prototype property, which only returns its own property. The value of the internal property [[[Enumerable]] of all enumerable properties is true.

var per3 = {    name:"pomy",    Blog:"http://www.ido321.com", age    :22 ,    getage:function() {        returnthis. age;    }};

In fact, the value of [[Enumerable]] for most native properties is false, that is, the property cannot be enumerated. You can detect whether a property can be enumerated by propertyisenumerable ():

Console.log (per3.propertyisenumerable ("name"));  // true var pros = Object.keys (PER3);  // returns an array of names of enumerable properties  in pros);  // trueconsole.log (pros.propertyisenumerable ("Length"));  // false

The property name is custom, enumerable, and the property length is a built-in property of Array.prototype and is not enumerable.

Property type

There are two types of properties: Data properties and accessor properties. Both have four attribute characteristics:

    • Data properties: [[[Enumerable]], [[Configurable]], [[Value]], and [[writable]]
    • Accessor properties: [[[Enumerable]], [[Configurable]], [[Get]], and [[Set]]

[[Enumerable]]: Boolean value, whether the property is enumerable, the custom property defaults to True.

[[[Configurable]]: Boolean value, whether the property can be configured (modifiable or removable), the custom property defaults to True. It is irreversible, that is set to false, and then set to True to error.

[[value]]: Saves the value of the property.

[[Writable]]: Boolean value, whether the property is writable, and all properties are writable by default.

[[get]]: Gets the property value.

[[Set]]: Sets the property value.

ES 5 provides two methods for setting these internal properties:

Object.defineproperty (Obj,pro,desc_map) and Object.defineproperties (Obj,pro_map). Use these two methods to add a property to Per3 and create a new object per4:

Object.defineproperty (Per3, "sex", {value:"Male", Enumerable:false, Configurable:false,//property cannot be deleted and modified, nor can the value be set to True}); Console.log (Per3.sex); //' Male 'Console.log (per3.propertyisenumerable ("Sex"));//falseDeletePer3.sex;//Cannot deletePer3.sex = "female";//cannot be modifiedConsole.log (Per3.sex);//' Male 'Object.defineproperty (Per3, "sex", {configurable:true,//Error});p Er4={};object.defineproperties (per4,{name:{value:"Dwqs", writable:true}, blog:{value:"Http://blog.92fenxiang.com"}, name:{get:function(){            return  This. Name; }, set:function(value) { This. Name =value; }, Enumerable:true, Configurable:true}}); Console.log (Per4.name); //DwqsPer4. Name = "Pomy"; Console.log (per4. Name); //pomy

It is important to note that when you define a new property in either of these ways, if you do not specify a feature value, the default is False, and you cannot create properties that have both data characteristics and accessor characteristics. The Object.getownpropertydescriptor () method can be used to obtain a description of the attribute characteristics, which accepts two parameters: Object and property name. If the property exists, the property description object is returned.

var desc = object.getownpropertydescriptor (per4, "name"//false//  False//true

Depending on the property type of the property, the property description object that is returned contains its corresponding four attribute characteristics.

Disallow modification of objects

Objects and properties have internal characteristics that guide their behavior. where [[extensible]] is a Boolean value that indicates whether the object itself can be modified ([[[Extensible]] value is true). The objects you create are extensible by default, and you can add new properties at any time.

ES5 is available in three ways:

    • Object.preventextensions (obj): Creates a non-extensible obj object that can be used with object.isextensible (obj) to detect if obj can be extended. Adding a property to a non-extended object in strict mode will give an error, and the addition fails in non-strict mode.
    • Object.seal (obj): The seal object, at which point the property of obj becomes read-only, cannot add, change, or delete properties (all properties are not configurable), and its [[extensible]] value is false,[[configurable]] value is false. You can use object.issealed (obj) to detect if obj is sealed.
    • Object.freeze (obj): Freezes an object, cannot add or remove properties on a frozen object, cannot change the property type, and cannot write to any data type. You can use Object.isfrozen (obj) to detect if obj is frozen. Note: Both frozen and sealed objects are used in strict mode.
"Use Strict";varPer5 ={name:"Pomy"};console.log (object.isextensible (PER5)); //trueConsole.log (object.issealed (PER5));//falseConsole.log (Object.isfrozen (PER5));//falseObject.freeze (PER5); Console.log (Object.isextensible (PER5)); //falseConsole.log (object.issealed (PER5));//trueConsole.log (Object.isfrozen (PER5));//truePer5.name= "Dwqs"; Console.log (per5.name); //"Pomy"Per5. Hi =function() {Console.log ("Hi");}; Console.log ("Hi"inchPER5);//falseDeletePer5.name;console.log (per5.name); //"Pomy"vardesc = Object.getownpropertydescriptor (per5, "name"); Console.log (desc.configurable); //falseConsole.log (desc.writable);//false

Note that the three methods that prohibit the modification of an object are valid only for the object's own property, the properties of the prototype object are not valid, and the properties can still be added or modified on the prototype.

function Person (name) {    this. Name = name;}  var New Person ("pomy"); var New Person ("Dwqs"function() {    console.log ("Hi");}; Person1. Hi ();   // "Hi"; Person2. Hi ();  // "Hi";

Reprint: Http://www.tuicool.com/articles/R7VvimQ---Cool push pomy ' s blog

JavaScript Object-oriented essentials (i)

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.