Home > Article > Web Front-end > Detailed explanation of the use of JS object-oriented
This time I will bring you a detailed explanation of the use of JS object-oriented. What are the precautions when using JS object-oriented. The following is a practical case, let's take a look.
In JavaScript, data types are divided into two categories:
Original type
Save some simple data, such as true, 5, etc. There are 5 primitive types in JavaScript:
boolean: Boolean, the value is true or false
number: number, the value is any integer or floating point value
string: string, the value is a single character or consecutive characters enclosed by single or double quotes ( JavaScript does not distinguish between character types)
null: empty type, which has only one value: nullll
undefined: undefined, which has only one value: undefined
var name = "Pomy"; var blog = "http://www.ido321.com"; var age = 22; alert(typeof blog); //"string" alert(typeof age); //"number"
Values of primitive types are stored directly in variables and can be detected using typeof. But typeof's detection of null returns object instead of null:
//弹出Not null if(typeof null){ alert("Not null"); }else{ alert("null"); }
Therefore, when detecting null, it is best to use all equals (===), which can also avoid forced type conversion:
console.log("21" === 21); //false console.log("21" == 21); //true console.log(undefined == null); //true console.log(undefined === null); //false
For strings, numbers or Boolean values, there are corresponding methods, which come from the corresponding primitive encapsulated types: String, Number and Boolean. The original encapsulation type will be created automatically.
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 to the string object is destroyed immediately after use, so attributes cannot be added to the string, and instanceof returns false when detecting the corresponding type:
var name = "Pomy"; name.age = 21; console.log(name.age); //undefined console.log(name instanceof String); //false
Reference type
Saving as an object is essentially a reference to a memory location, so the object is not saved in a variable. In addition to custom objects, JavaScript provides 6 built-in types:
Array: Array type, an ordered list of a set of values indexed by number
Date: Date and time type
Error: Runtime error type
Function: Function type
Object: Generic object type
RegExp:Regular expressionType
You can use new to instantiate each object, or use literal form to create objects:
var obj = new Object; var own = { name:"Pomy", blog:"http://www.ido321.com", "my age":22 }; console.log(own.blog); //访问属性 console.log(own["my age"]); obj = null; //解除引用
obj does not contain an object instance, but a pointer (or reference) to the location of the actual object in memory. Because typeof returns object for all non-function reference types, instanceof needs to be used to detect the reference type.
Function
In JavaScript, functions are objects. The defining property that makes functions different from other objects is the presence of an internal property called [[Call]]. Internal properties are not accessible through code but define the behavior when the code is executed.
Create form
1. Function declaration: using the function keyword will be promoted to the context
2. Function expression: cannot be promoted
3. Instantiate the Function built-in type
sayHi(); //函数提升 function sayHi(){ console.log("Hello"); } //其他等效等效方式 /* var sayHi = function(){ console.log("Hello"); } var sayHi = new Function(" console.log(\"Hello\");"); */
Parameters
Another unique feature of JavaScript functions is that you can pass any number of parameters to the function. Function parameters are stored in an array object of the arguments class, which automatically exists in the function. The parameters can be referenced by numerical index, but it is not an array instance:
alert(Array.isArray(arguments)); //false
The array object arguments saves the actual parameters of the function, but the formal parameters are not ignored. Thus, arguments.length returns the length of the actual parameter list, and arguments.callee.length returns the length of the formal parameter list.
function ref(value){ return value; } console.log(ref("Hi")); console.log(ref("Hi",22)); console.log(ref.length); //1
this in function
For questions about this, please refer to this article: this in JavaScript.
JavaScript provides three methods for changing the pointer of this: call, apply and bind. The first parameter of the three functions all specifies the value of this, and the other parameters are passed to the function as parameters.
Object
Object is a reference type. There are two common ways 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 = "不写代码的码农";
Attribute operation
In JavaScript, you can add properties to an object at any time:
per1.age = 0; per1.sayName = function(){ alert(this.name); //"Pomy" }
因而,在检测对象属性是否存在时,常犯的一个错误是:
//结果是false if(per1.age){ alert(true) }else{ alert(false); }
per1.age 是存在的,但是其值是0,所以不能满足if条件。if判断中的值是一个对象、非空字符串、非零数字或true时,判断会评估为真;而当值是一个null、undefined、0、false、NaN或空字符串时评估为假。
因而,检测属性是否存在时,有另外的两种方式:in和hasOwnProperty(),前者会检测原型属性和自有(实例)属性,后者只检测自有(实例)属性。
console.log("age" in per1); //true console.log(per1.hasOwnProperty("age")); //true console.log("toString" in per1); //true console.log(per1.hasOwnProperty("toString")); //false
对象per1并没有定义toString,该属性继承于Object.prototype,所以in和hasOwnProperty()检测该属性时出现差异。如果只想判断一个对象属性是不是原型,可以利用如下方法:
function isPrototypeProperty(obj,name){ return name in obj && !obj.hasOwnProperty(name); }
若要删除一个属性,用delete操作符,用于删除自有属性,不能删除原型属性。
per1.toString = function(){ console.log("per1对象"); }; console.log(per1.hasOwnProperty("toString")); //true per1.toString(); //"per1对象" delete per1.toString; console.log(per1.hasOwnProperty("toString")); //false console.log(per1.toString()); //[object Object]
有时需要枚举对象的可枚举属性,也有两种方式:for-in循环和Object.keys(),前者依旧会遍历出原型属性,后者只返回自有属性。所有可枚举属性的内部属性[[Enumerable]]的值均为true。
var per3 = { name:"Pomy", blog:"http://www.ido321.com", age:22, getAge:function(){ return this.age; } };
实际上,大部分原生属性的[[Enumerable]]的值均为false,即该属性不能枚举。可以通过propertyIsEnumerable()检测属性是否可以枚举:
console.log(per3.propertyIsEnumerable("name")); //true var pros = Object.keys(per3); //返回可枚举属性的名字数组 console.log("length" in pros); //true console.log(pros.propertyIsEnumerable("length")); //false
属性name是自定义的,可枚举;属性length是Array.prototype的内建属性,不可枚举。
属性类型
属性有两种类型:数据属性和访问器属性。二者均具有四个属性特征:
数据属性:[[Enumerable]]、[[Configurable]]、[[Value]]和[[Writable]]
访问器属性:[[Enumerable]]、[[Configurable]]、[[Get]]和[[Set]]
**[[Enumerable]] :**布尔值,属性是否可枚举,自定义属性默认是true。
**[[Configurable]] :**布尔值,属性是否可配置(可修改或可删除),自定义属性默认是true。它是不可逆的,即设置成false后,再设置成true会报错。
**[[Value]]:**保存属性的值。
**[[Writable]]:**布尔值,属性是否可写,所有属性默认可写。
**[[Get]]:**获取属性值。
**[[Set]]:**设置属性值。
ES 5提供了两个方法用于设置这些内部属性:
Object.defineProperty(obj,pro,desc_map) 和 Object.defineProperties(obj,pro_map)。利用这两个方法为per3添加一个属性和创建一个新对象per4:
Object.defineProperty(per3,"sex",{ value:"male", enumerable:false, configurable:false, //属性不能删除和修改,该值也不能被设置成true }); console.log(per3.sex); //'male' console.log(per3.propertyIsEnumerable("sex")); //false delete per3.sex; //不能删除 per3.sex = "female"; //不能修改 console.log(per3.sex); //'male' Object.defineProperty(per3,"sex",{ configurable:true, //报错 }); 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, configurable:true } }); console.log(per4.name); //dwqs per4.Name = "Pomy"; console.log(per4.Name); //Pomy
需要注意的是,通过这两种方式来定义新属性时,如果不指定特征值,则默认是false,也不能创建同时具有数据特征和访问器特征的属性。可以通过Object.getOwnPropertyDescriptor()方法来获取属性特征的描述,接受两个参数:对象和属性名。若属性存在,则返回属性描述对象。
var desc = Object.getOwnPropertyDescriptor(per4,"name"); console.log(desc.enumerable); //false console.log(desc.configurable); //false console.log(desc.writable); //true
根据属性的属性类型,返回的属性描述对象包含其对应的四个属性特征。
禁止修改对象
对象和属性一样具有指导其行为的内部特征。其中,[[Extensible]]是一个布尔值,指明改对象本身是否可以被修改([[Extensible]]值为true)。创建的对象默认都是可以扩展的,可以随时添加新的属性。
ES5提供了三种方式:
Object.preventExtensions(obj):创建不可扩展的obj对象,可以利用Object.isExtensible(obj)来检测obj是否可以扩展。严格模式下给不扩展对象添加属性会报错,非严格模式下则添加失败。
Object.seal(obj):封印对象,此时obj的属性变成只读,不能添加、改变或删除属性(所有属性都不可配置),其[[Extensible]]值为false,[[Configurable]]值为false。可以利用Object.isSealed(obj)来检测obj是否被封印。
Object.freeze(obj):冻结对象,不能在冻结对象上添加或删除属性,不能改变属性类型,也不能写入任何数据类型。可以利用Object.isFrozen(obj)来检测obj是否被冻结。
注意:冻结对象和封印对象均要在严格模式下使用。
"use strict"; var per5 = { name:"Pomy" }; console.log(Object.isExtensible(per5)); //true console.log(Object.isSealed(per5)); //false console.log(Object.isFrozen(per5)); //false Object.freeze(per5); console.log(Object.isExtensible(per5)); //false console.log(Object.isSealed(per5)); //true console.log(Object.isFrozen(per5)); //true per5.name="dwqs"; console.log(per5.name); //"Pomy" per5.Hi = function(){ console.log("Hi"); }; console.log("Hi" in per5); //false delete per5.name; console.log(per5.name); //"Pomy" var desc = Object.getOwnPropertyDescriptor(per5,"name"); console.log(desc.configurable); //false console.log(desc.writable); //false
注意,禁止修改对象的三个方法只对对象的自有属性有效,对原型对象的属性无效,仍然可以在原型上添加或修改属性。
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";
补充:
Object.seal(obj): Seals the object. At this time, the properties of obj become read-only. Properties cannot be added, changed or deleted (all properties are not configurable). Its [[Extensible]] value is false, [[Configurable]] The value is false. You can use Object.isSealed(obj) to detect whether obj is sealed.
This is easy to make people ambiguous. Generally speaking, attributes can be easily understood by us as their values.
, I hope the author can modify it a little to make it easier to understand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal
I prefer to understand
Object.freeze frozen objects in reverse, No addition, deletion or modification of any attributes or attribute values is allowed.
Object.seal is a closed object. Compared with Object.freeze, it can modify the value of existing properties.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps of using Mixins in Vue.js
How to implement weight probability sorting of js arrays
The above is the detailed content of Detailed explanation of the use of JS object-oriented. For more information, please follow other related articles on the PHP Chinese website!