JavaScript object-oriented (1)
Data Type
In JavaScript, there are two types of data:
Original Type: Save some simple data, such
true,
5. JavaScript has a total of 5 primitive types:
boolean: Boolean; value:
trueOr
false
number: Number. If the value is any integer, it will be a floating point value.
string: String, which is a single character or continuous character enclosed by single or double quotation marks (JavaScript does not differentiate character types)
null: Null type, which has only one value:
nulll
undefined: Undefined, with only one value:
undefined
var name = "Pomy";var blog = "http://www.ido321.com";var age = 22;alert(typeof blog); //"string"alert(typeof age); //"number"
The value of the original type is saved directly in the variable and can be usedtypeof. HowevertypeofPairnullIs returnedobjectInstead of returningnull:
// The Not nullif (typeof null) {alert ("Not null") ;}else {alert ("null ");}
So DetectionnullIt is best to use full equals (=), which can avoid forced type conversion:
console.log("21" === 21); //falseconsole.log("21" == 21); //trueconsole.log(undefined == null); //trueconsole.log(undefined === null); //false
There are corresponding methods for strings, numbers, or boolean values. These methods come from the corresponding original encapsulation type:String,NumberAndBoolean. The original encapsulation type is automatically created.
var name = "Pomy";var char = name.charAt(0);console.log(char); //"P"
What happens in the JavaScript engine:
var name = "Pomy";var temp = new String(name);var char = temp.charAt(0);temp = null;console.log(char); //"P"
The reference of a string object is destroyed immediately after it is used up. Therefore, attributes cannot be added to the string, andinstanceofReturns results when detecting corresponding typesfalse:
var name = "Pomy";name.age = 21;console.log(name.age); //undefinedconsole.log(name instanceof String); //false
Reference Type: Save as an object. It is actually a reference pointing to the memory location. Therefore, the object is not saved in the variable. In addition to custom objects, JavaScript provides the following built-in types:
Array: An ordered list of values of the array type indexed by numbers
Date: Date and Time Type
Error: Error Type during runtime
Function: Function Type
Object: Common Object Type
RegExp: Regular Expression type
Available
newTo instantiate an object or create an object in the literal form:
Var obj = new Object; var own = {name: "Pomy", blog: "http://www.ido321.com", "my age": 22}; console. log (own. blog); // access the property console. log (own ["my age"]); obj = null; // unreference
objIt does not contain object instances, but a pointer (or reference) pointing to the location of the actual object in the memory ). BecausetypeofReturns the reference type of all non-functions.object, So you need to useinstanceofTo detect the reference type.
Function
In JavaScript, a function is an object. Unlike other objects, a function is called[[Call]]. Internal properties cannot be accessed through code, but define the behavior during code execution.
Creation form
1. function declaration: UsefunctionKeyword, will be promoted to the context
2. function expression: cannot be promoted
3. instantiationFunctionBuilt-in type
SayHi (); // function upgrade function sayHi () {console. log ("Hello");} // other equivalent methods/* var sayHi = function () {console. log ("Hello");} var sayHi = new Function ("console. log (\ "Hello \");");*/
Parameters
Another unique feature of JavaScript Functions is that they can pass any number of parameters to functions. Function parameters are stored inargumentsIn an array object of the class, it automatically exists in the function and can reference parameters through digital indexes, but it is not an array instance:
alert(Array.isArray(arguments)); //false
Class array objectargumentsThe real parameters of the function are saved, but the parameters are not ignored. Therefore,arguments.lengthReturns the length of the real parameter list,arguments.callee.lengthThe length of the returned parameter list.
function ref(value){ return value;}console.log(ref("Hi"));console.log(ref("Hi",22));console.log(ref.length); //1
This in the function
AboutthisFor more information, see this in JavaScript.
JavaScript provides three methods for changingthisPoint:call,applyAndbind. The first parameter of the three functions is specified.thisOther parameters are passed to the function as parameters.
Object
An object is a reference type. There are two common methods to create an object:ObjectConstructor and object literal form:
Var per1 = {name: "Pomy", blog: "http://www.ido321.com"}; var per2 = new Object; per2.name = "codeph without code writing ";
Attribute operations
In JavaScript, you can add attributes to an object at any time:
per1.age = 0;per1.sayName = function(){ alert(this.name); //"Pomy"}
Therefore, when detecting whether an object property exists, the common mistake is:
// The result is falseif (per1.age) {alert (true)} else {alert (false );}
per1.ageYes, but its value is 0, so it cannot meetifCondition.ifThe value in the determination is an object, a non-null string, a non-zero number, ortrueThe evaluation is true, while the value isnull,undefined,0,false,NaNOr a null string is evaluated as false.
Therefore, there are two ways to check whether a property exists:inAndhasOwnProperty()The former detects the prototype attributes and its own (Instance) attributes, while the latter only detects its own (Instance) attributes.
console.log("age" in per1); //trueconsole.log(per1.hasOwnProperty("age")); //trueconsole.log("toString" in per1); //trueconsole.log(per1.hasOwnProperty("toString")); //false
Objectper1Not DefinedtoStringThis property is inherited fromObject.prototype, SoinAndhasOwnProperty()This attribute is different when detected. If you only want to determine whether an object property is prototype, you can use the following method:
function isPrototypeProperty(obj,name){ return name in obj && !obj.hasOwnProperty(name);}
To delete an attribute, usedeleteOperator, used to delete self-owned attributes, cannot delete prototype attributes.
Per1.toString = 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]
You can use either of the following methods to enumerate the enumerated attributes of an object:for-inLoop andObject.keys()The former will still traverse the prototype attributes, and the latter will only return its own attributes. Internal properties of all enumerable Properties[[Enumerable]]Aretrue.
var per3 = { name:"Pomy", blog:"http://www.ido321.com", age:22, getAge:function(){ return this.age; }};
In fact, most native attributes[[Enumerable]]ArefalseThat is, this attribute cannot be enumerated. You can usepropertyIsEnumerable()Check whether the attributes can be enumerated:
Console. log (per3.propertyIsEnumerable ("name"); // truevar pros = Object. keys (per3); // returns the name array console of the enumerated attribute. log ("length" in pros); // trueconsole. log (pros. propertyIsEnumerable ("length"); // false
AttributenameIs custom, enumerable; AttributelengthYesArray.prototypeThe built-in attributes of cannot be enumerated.
Attribute type
There are two types of attributes: data attributes and accessors attributes. Both have four attributes:
Data attributes:
[[Enumerable]],
[[Configurable]],
[[Value]]And
[[Writable]]Accessors attributes:
[[Enumerable]],
[[Configurable]],
[[Get]]And
[[Set]]
[[Enumerable]: Boolean value. Whether the attribute can be enumerated. The default value of the custom attribute istrue.
[[Retriable]: Boolean value. Whether the property can be configured (can be modified or deleted). The default value of the custom property istrue. It is irreversible, that is, setfalseAnd then settrueAn error is reported.
[[Value]: Save the attribute value.
[[Writable]: Boolean value. Whether the attribute is writable. All attributes are writable by default.
[[Get]: Get the property value.
[[Set]: Set the property value.
ES 5 provides two methods to set these internal attributes:
Object.defineProperty(obj,pro,desc_map)AndObject.defineProperties(obj,pro_map). Use these two methodsper3Add an attribute and create a new objectper4:
Object. defineProperty (per3, "sex", {value: "male", enumerable: false, retriable: false, // attributes cannot be deleted or modified, this value cannot be set to true}); console. log (per3.sex); // 'male' console. log (per3.propertyIsEnumerable ("sex"); // falsedelete per3.sex; // per3.sex = "female" cannot be deleted; // The console cannot be modified. log (per3.sex); // 'male' Object. defineProperty (per3, "sex", {retriable: true, // error reported}); per4 = {}; 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, retriable: true }}); console. log (per4.name); // dwqsper4.Name = "Pomy"; console. log (per4.Name); // Pomy
Note that when defining a new attribute using these two methods, if the feature value is not specified, the default value isfalseAnd cannot create attributes with both data features and accessors features.. You can useObject.getOwnPropertyDescriptor()Method to obtain the description of the attribute feature. Two parameters are accepted: object and attribute name. If an attribute exists, the property description object is returned.
var desc = Object.getOwnPropertyDescriptor(per4,"name");console.log(desc.enumerable); //falseconsole.log(desc.configurable); //falseconsole.log(desc.writable); //true
Based on the attribute type, the returned attribute description object contains four attribute features.
Object modification prohibited
Objects have the same internal characteristics as attributes that guide their behaviors. Where,[[Extensible]]Is a Boolean value that specifies whether the object itself can be modified ([[Extensible]]The value istrue). By default, all created objects can be expanded and new attributes can be added at any time.
ES5 provides three methods:
Object.preventExtensions(obj): Create non-extensible obj objects, which can be used
Object.isExtensible(obj)To check whether obj can be extended. In strict mode, an error is returned when you add attributes to a non-extended object. In non-strict mode, the addition fails.
Object.seal(obj): Seal the object. In this case, the property of obj becomes read-only and cannot be added, changed, or deleted (all properties cannot be configured ).
[[Extensible]]The value is
false,
[[Configurable]]The value is
false. Available
Object.isSealed(obj)To check whether obj is blocked.
Object.freeze(obj): Freeze object. You cannot add or delete properties on frozen objects. You cannot change the property type or write any data type. Available
Object.isFrozen(obj)To check whether obj is frozen.
Note: Freeze objects and seal objects must be used in strict mode.
"use strict";var per5 = { 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" in per5); //falsedelete per5.name;console.log(per5.name); //"Pomy"var desc = Object.getOwnPropertyDescriptor(per5,"name");console.log(desc.configurable); //falseconsole.log(desc.writable); //false
Note,The three methods to prohibit object modification are only valid for the attributes of the object and invalid for the attributes of the prototype object. You can still add or modify attributes on the prototype..
function Person(name){ this.name = name;}var person1 = new Person("Pomy");var person2 = new Person("dwqs");Object.freeze(person1);Person.prototype.Hi = function(){ console.log("Hi");};person1.Hi(); //"Hi";person2.Hi(); //"Hi";
Original article: http://www.ido321.com/1585.html
Related Articles:
DOM note (9): reference type, basic packaging type, and single built-in object
DOM note (11): basic understanding and creation of JavaScript objects