This article introduces JavaScript object-oriented data types.
In JavaScript, there are two types of data:
Original Type: Save some simple data, such as true and 5. JavaScript has a total of 5 primitive types:
● Boolean: boolean. The value is true or false.
● Number: number. If the value is any integer, it indicates a floating point value.
● String: string, which is a single character or continuous character enclosed by single quotation marks or double quotation marks (JavaScript does not differentiate character types)
● Null: null type, with 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 directly stored in the variable and can be detected using typeof. However, if typeof detects null, it returns an object instead of null:
// The Not nullif (typeof null) {alert ("Not null") ;}else {alert ("null ");}
Therefore, when detecting null, it is best to use all equal to (=), 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 primitive encapsulation types: String, Number, and Boolean. 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. If instanceof detects the corresponding type, false is returned:
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 a group of values indexed by numbers.
● Date: Date and Time Type
● Error: Error Type during runtime
● Function: Function Type
● Object: Common Object Type
● RegExp: Regular Expression type
You can use new to instantiate each object, or use a literal to create an object:
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
Obj does not contain object instances, but a pointer (or reference) pointing to the location of the actual object in the memory ). Because typeof returns an object for all non-function reference types, you need to use instanceof to detect the reference type.
Function
In JavaScript, a function is an object. Unlike other objects, a function has an internal attribute called [Call. Internal properties cannot be accessed through code, but define the behavior during code execution.
Creation form
1. function declaration: The function keyword is promoted to the context.
2. function expression: cannot be promoted
3. instantiate the built-in Function 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. The function parameter is saved in the arguments array object. It automatically exists in the function and can reference the parameter through a digital index, but it is not an array instance:
alert(Array.isArray(arguments)); //false
Class array object arguments stores the real parameters of the function, but does not ignore the form parameters. Therefore, arguments. length returns the length of the real parameter list, and arguments. callee. length returns the length of the form 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
For more information about this, see this in JavaScript.
JavaScript provides three methods to change the point of this: call, apply, and bind. The first parameter of the three functions specifies the value of this. Other parameters are passed to the function as parameters.
Object
An Object is a reference type. There are two common methods to create an Object: Object constructor 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.age exists, but its value is 0, so it cannot meet the if condition. If the value in the judgment is an object, non-null string, non-zero number or true, the judgment will be evaluated as true; when the value is a null, undefined, 0, false, NaN, or null string, it is evaluated as false.
Therefore, when detecting whether a property exists, there are two other methods: in and hasOwnProperty (). The former will detect the prototype property and its own (Instance) property, 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
The Object per1 does not define toString. This property inherits from Object. prototype, so in and hasOwnProperty () are different when detecting this property. 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, use the delete operator to delete its own attribute. You cannot delete the prototype attribute.
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-in loop or Object. keys (), the former will still traverse the prototype attributes, and the latter will only return its own attributes. The value of [[Enumerable] is true for all the internal properties that can be enumerated.
var per3 = {name:"Pomy",blog:"http://www.ido321.com",age:22,getAge:function(){return this.age;}};
In fact, the value of [[Enumerable] For most native attributes is false, that is, this attribute cannot be enumerated. You can use propertyIsEnumerable () to check whether 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
The property name is customized and can be enumerated. The property length is a built-in property of Array. prototype and cannot be enumerated.
Attribute type
There are two types of attributes: data attributes and accessors attributes. Both have four attributes:
● Data attributes: [[Enumerable], [[retriable], [Value], and [[Writable]
● Accessors: [[Enumerable], [[retriable], [Get], and [[Set]
[[Enumerable]: Boolean value. Whether the attribute can be enumerated. The default value of the custom attribute is true. [[Retriable]: Boolean value. Whether the property can be configured (can be modified or deleted). The default value of the custom property is true. It is irreversible. If it is set to false, an error is returned if it is set to true.
[[Value]: Save the attribute Value.
[[Writable]: Boolean value. It indicates whether the attribute can be written. All attributes can be written by default.
[[Get]: Get the property value.
[[Set]: Set the attribute value.
ES 5 provides two methods to set these internal attributes:
Object. defineProperty (obj, pro, desc_map) and Object. defineProperties (obj, pro_map ). Use these two methods to add an attribute for per3 and create a new object per4:
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
When defining a new attribute using these two methods, if the feature value is not specified, the default value is false. You cannot create an attribute with both data features and accessors features. You can use the Object. getOwnPropertyDescriptor () method to obtain the description of attribute features. 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. [[Extensible] is a Boolean value that specifies whether the object itself can be modified ([Extensible] value is true ). By default, all created objects can be expanded and new attributes can be added at any time.
ES5 provides three methods:
● Object. preventExtensions (obj): creates an unextensible obj Object. You can use Object. isExtensible (obj) to check whether obj can be expanded. 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): Specifies the object to be seed. In this case, the property of obj is read-only and cannot be added, changed, or deleted. (All properties cannot be configured.) The value of [[Extensible] is false, the value of [[retriable] is false. You can use Object. isSealed (obj) to check whether obj is blocked.
● Object. freeze (obj): freeze an Object. You cannot add or delete properties on the freeze Object, change the property type, or write any data type. You can use Object. isFrozen (obj) to check whether the Object 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";
Constructor and prototype object
Constructor is also a function called when an object is created using new. The difference between a constructor and a common function is that the first letter of the constructor should be capitalized. If the constructor is called as a common function (the new Keyword is missing), pay attention to the issue pointed to by this.
var name = "Pomy";function Per(){console.log("Hello "+this.name);}var per1 = new Per(); //"Hello undefined"var per2 = Per(); //"Hello Pomy"
When new is used, this object is automatically created, and its type is constructor type, pointing to the object instance. If the new keyword is missing, this points to the global object.
You can use instanceof to detect Object types. At the same time, each Object automatically has a constructor attribute when it is created, pointing to its constructor (an Object created by a literal or Object constructor pointing to an Object, the object created by the custom constructor points to its constructor ).
console.log(per1 instanceof Per); //trueconsole.log(per1.constructor === Per); //true
Each object instance has an internal attribute [[Prototype] pointing to the Prototype of the object. Constructors also have prototype attributes pointing to prototype objects. All created objects share the attributes and methods of the prototype object.
function Person(){}Person.prototype.name="dwqs";Person.prototype.age=20;Person.prototype.sayName=function(){alert(this.name);};var per1 = new Person();per1.sayName(); //dwqsvar per2 = new Person();per2.sayName(); //dwqsalert(per1.sayName == per2.sayName); //true
alert(Person.prototype.isPrototypeOf(per2)); //trueper1.blog = "www.ido321.com";alert(per1.hasOwnProperty("blog")); //truealert(Person.prototype.hasOwnProperty("blog")); //falsealert(per1.hasOwnProperty("name")); //falsealert(Person.prototype.hasOwnProperty("name")); //true
Because the constructor attribute of the prototype object points to the constructor itself, you need to pay attention to the constructor attribute points to the problem when rewriting the prototype.
Function Hello (name) {this. name = name;} // rewrite the prototype Hello. prototype = {sayHi: function () {console. log (this. name) ;}}; var hi = new Hello ("Pomy"); console. log (hi instanceof Hello); // trueconsole. log (hi. constructor === Hello); // falseconsole. log (hi. constructor === Object); // true
Using the Object literal form, the prototype Object changes the attributes of the constructor, so the constructor points to the Object instead of Hello. If the constructor points to a very important point, you need to manually reset its constructor attribute when rewriting the prototype object.
Hello.prototype = {constructor:Hello,sayHi:function(){console.log(this.name);}};console.log(hi.constructor === Hello); //trueconsole.log(hi.constructor === Object); //false
Using the features of the prototype object, we can easily add custom methods to the JavaScript built-in prototype object:
Array.prototype.sum=function(){return this.reduce(function(prev,cur){return prev+cur;});};var num = [1,2,3,4,5,6];var res = num.sum();console.log(res); //21String.prototype.capit = function(){return this.charAt(0).toUpperCase()+this.substring(1);};var msg = "hello world";console.log(msg.capit()); //"Hello World"
Inheritance
The [[Prototype] feature enables Prototype inheritance. Objects in the literal form are implicitly specified. prototype is its [[Prototype]. You can also use Object. the create () parameter specifies the display. It accepts two parameters: the first is the object directed to [Prototype] (Prototype object), and the second is the optional attribute descriptor object.
Var book = {title: "This is the title of the book" ;}; // same as the following method var book = Object. create (Object. prototype, {title: {retriable: true, enumerable: true, value: "This is the title", wratable: true }});
The literal Object inherits from the Object by default. More interesting usage is to implement inheritance between custom objects.
Var book1 = {title: "JS advanced programming", getTitle: function () {console. log (this. title) ;}}; var book2 = Object. create (book1, {title: {retriable: true, enumerable: true, value: "JS authoritative guide", wratable: true}); book1.getTitle (); // "JS advanced programming" book2.getTitle (); // "JS authoritative guide" console. log (book1.hasOwnProperty ("getTitle"); // trueconsole. log (book1.isPrototypeOf ("book2"); // falseconsole. log (book2.hasOwnProperty ("getTitle"); // false
When you access the getTitle attribute of book2, the JavaScript engine performs a search process: search for its own attribute in book2. If it is found, use it. If it is not found, search for [Prototype]. if no Prototype is found, search for [[Prototype] of the Prototype object until the end of the inheritance chain. The end is usually Object. prototype. Its [[Prototype] is set to null.
Another way to implement inheritance is to use constructor. Each function has a writable prototype attribute. By default, it is set to inherit from Object. prototype. You can modify it to change the prototype chain.
Function Rect (length, width) {this. length = length; this. width = width;} Rect. prototype. getArea = function () {return this. width * this. length ;}; Rect. prototype. toString = function () {return "[Rect" + this. length + "*" + this. width + "]" ;}; function Square (size) {this. length = size; this. width = size;} // modify the prototype attribute Square. prototype = new Rect (); Square. prototype. constructor = Square; Square. prototype. toString = function () {return "[Square" + this. length + "*" + this. width + "]" ;}; var rect = new Rect (5, 10); var square = new Square (6); console. log (rect. getArea (); // 50console. log (square. getArea (); // 36
If you want to access the toString () of the parent class, you can do this:
Square.prototype.toString = function(){var text = Rect.prototype.toString.call(this);return text.replace("Rect","Square");}
For more JavaScript object-oriented articles, please follow the PHP Chinese network!