Home > Web Front-end > JS Tutorial > body text

JavaScript Object-Oriented Essentials (1)

黄舟
Release: 2017-03-06 14:32:46
Original
1176 people have browsed it

Data type

In JavaScript, data types are divided into two categories:

Primitive 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 Floating point numberValue

  • string: String, the value is a single character or consecutive characters enclosed by single or double quotes (JavaScript does not distinguish 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"
Copy after login

The value of the original type is stored directly in the variable and can be detected using typeof. However, typeof's detection of null returns object instead of null:

//弹出Not null
if(typeof null){
    alert("Not null");   
}else{
    alert("null");
}
Copy after login

So 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
Copy after login

For strings, numbers or Boolean values, there are corresponding methods, which come from the corresponding original encapsulation 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"
Copy after login

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"
Copy after login

The reference to the string object is destroyed immediately after use, so attributes cannot be added to the string, and instanceof detects the corresponding type evenly Return false:

var name = "Pomy";
name.age = 21;
console.log(name.age);   //undefined
console.log(name instanceof String);  //false
Copy after login

Reference type

is saved as an object, which 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 numbers

  • Date: Date and time type

  • Error: Runtime error type

  • Function: Function type

  • Object: General object type

  • RegExp: Regular expression type

You can use new to instantiate each An object, or creating an object in literal form:

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;  //解除引用
Copy after login

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: Use the function keyword, which will be promoted to the context
2. Function expression: cannot be promoted
3. Instantiation within Function Create type

sayHi();    //函数提升
function sayHi(){
    console.log("Hello");
}
//其他等效等效方式
/*
var sayHi = function(){
     console.log("Hello");
}
var sayHi = new Function(" console.log(\"Hello\");");
*/
Copy after login

Parameters

Another unique feature of JavaScript functions is that you can pass any number of parameters to the function. Function parameters are stored in the arguments class array object, which automatically exists in the function. The parameters can be referenced through numerical indexes, but it is not an array instance:

alert(Array.isArray(arguments));   //false
Copy after login

The arguments class array object stores 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
Copy after login

This in the 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 = "不写代码的码农";
Copy after login

Property operation

In JavaScript, you can add attributes to objects at any time:

per1.age = 0;
per1.sayName = function(){
    alert(this.name);   //"Pomy"
}
Copy after login

Therefore, when detecting whether object attributes exist, a common mistake is:

//结果是false
if(per1.age){
    alert(true)
}else{
    alert(false);
}
Copy after login

per1.age does exist , 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-zero number, or true, the judgment will evaluate to true; and when the value is a null, undefined, 0, false, NaN, or an empty string, it will evaluate to false.

Therefore, there are two other ways to detect whether a property exists: in and hasOwnProperty(). The former will detect prototype properties and own (instance) properties, and the latter will only detect own (instance) properties. .

console.log("age" in per1);  //true
console.log(per1.hasOwnProperty("age"));  //true
console.log("toString" in per1);  //true
console.log(per1.hasOwnProperty("toString"));  //false
Copy after login

Object per1 does not define toString. This property is inherited from Object.prototype, so there are differences when in and hasOwnProperty() detect this property. If you only want to determine whether an object attribute is a prototype, you can use the following method:

function isPrototypeProperty(obj,name){
    return name in obj && !obj.hasOwnProperty(name);
}
Copy after login

To delete an attribute, use the delete operator, which is used to delete its own attributes. Prototype attributes cannot be deleted.

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]
Copy after login

Sometimes you need to enumerate the enumerable properties of an object. There are two ways: for-in loop and Object.keys(). The former will still traverse the prototype properties, and the latter will only return its own properties. 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(){
        return this.age;
    }
};
Copy after login

In fact, the value of [[Enumerable]] for most native attributes is false, that is, the attribute cannot be enumerated. You can check whether a property can be enumerated through propertyIsEnumerable():

console.log(per3.propertyIsEnumerable("name"));  //true
var pros = Object.keys(per3);  //返回可枚举属性的名字数组
console.log("length" in pros);  //true
console.log(pros.propertyIsEnumerable("length"));  //false
Copy after login

属性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
Copy after login

需要注意的是,通过这两种方式来定义新属性时,如果不指定特征值,则默认是false,也不能创建同时具有数据特征和访问器特征的属性。可以通过Object.getOwnPropertyDescriptor()方法来获取属性特征的描述,接受两个参数:对象和属性名。若属性存在,则返回属性描述对象。

var desc = Object.getOwnPropertyDescriptor(per4,"name");
console.log(desc.enumerable); //false
console.log(desc.configurable); //false
console.log(desc.writable); //true
Copy after login

根据属性的属性类型,返回的属性描述对象包含其对应的四个属性特征。

禁止修改对象

对象和属性一样具有指导其行为的内部特征。其中,[[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
Copy after login

注意,禁止修改对象的三个方法只对对象的自有属性有效,对原型对象的属性无效,仍然可以在原型上添加或修改属性。

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";
Copy after login

以上就是JavaScript 面向对象精要(一) 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!