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

JavaScript object-oriented essentials

高洛峰
Release: 2017-02-04 17:49:12
Original
1018 people have browsed it

Data types

In JavaScript, data types are divided into two categories:

Primitive types: 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 number

● 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, it 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 directly stored in the variable and can be detected with 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: 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: Common object type

●RegExp: Regular expression type

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

obj does not contain object instances, but Is 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. Example Function built-in 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 any number of parameters can be passed 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 objects: Object constructor and object literal form:

var per1 = {
name:"Pomy",
blog:"http://www.ido321.com"
};
var per2 = new Object;
per2.name = "不写代码的码农";
Copy after login

Attribute operation

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

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

Therefore, when detecting whether an object attribute exists, a common mistake is:

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

per1.age exists, 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 the 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

The property name is customized and can be enumerated; the property length is a built-in property of Array.prototype and cannot be enumerated.

Property Type

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

●数据属性:[[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

构造函数和原型对象

构造函数也是函数,用new创建对象时调用的函数,与普通函数的一个区别是,其首字母应该大写。但如果将构造函数当作普通函数调用(缺少new关键字),则应该注意this指向的问题。

var name = "Pomy";
function Per(){
console.log("Hello "+this.name);
}
var per1 = new Per(); //"Hello undefined"
var per2 = Per(); //"Hello Pomy"
Copy after login

使用new时,会自动创建this对象,其类型为构造函数类型,指向对象实例;缺少new关键字,this指向全局对象。


可以用instanceof来检测对象类型,同时每个对象在创建时都自动拥有一个constructor属性,指向其构造函数(字面量形式或Object构造函数创建的对象,指向Object,自定义构造函数创建的对象则指向它的构造函数)。

console.log(per1 instanceof Per); //true
console.log(per1.constructor === Per); //true
Copy after login

每个对象实例都有一个内部属性:[[Prototype]],其指向该对象的原型对象。构造函数本身也具有prototype属性指向原型对象。所有创建的对象都共享该原型对象的属性和方法。

function Person(){}
Person.prototype.name="dwqs";
Person.prototype.age=20;
Person.prototype.sayName=function()
{
alert(this.name);
};
var per1 = new Person();
per1.sayName(); //dwqs
var per2 = new Person();
per2.sayName(); //dwqs
alert(per1.sayName == per2.sayName); //true
Copy after login

JavaScript object-oriented essentials

所以,**实例中的指针仅指向原型,而不指向构造函数。**ES5提供了hasOwnProperty()和isPropertyOf()方法来反应原型对象和实例之间的关系

alert(Person.prototype.isPrototypeOf(per2)); //true
per1.blog = "www.ido321.com";
alert(per1.hasOwnProperty("blog")); //true
alert(Person.prototype.hasOwnProperty("blog")); //false
alert(per1.hasOwnProperty("name")); //false
alert(Person.prototype.hasOwnProperty("name")); //true
Copy after login

因为原型对象的constructor属性是指向构造函数本身,所以在重写原型时,需要注意constructor属性的指向问题。

function Hello(name){
this.name = name;
}
//重写原型
Hello.prototype = {
sayHi:function(){
console.log(this.name);
}
};
var hi = new Hello("Pomy");
console.log(hi instanceof Hello); //true
console.log(hi.constructor === Hello); //false
console.log(hi.constructor === Object); //true
Copy after login

使用对象字面量形式改写原型对象改变了构造函数的属性,因此constructor指向Object,而不是Hello。如果constructor指向很重要,则需要在改写原型对象时手动重置其constructor属性

Hello.prototype = {
constructor:Hello,
sayHi:function(){
console.log(this.name);
}
};
console.log(hi.constructor === Hello); //true
console.log(hi.constructor === Object); //false
Copy after login

利用原型对象的特性,我们可以很方便的在JavaScript的内建原型对象上添加自定义方法:

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); //21
String.prototype.capit = function(){
return this.charAt(0).toUpperCase()+this.substring(1);
};
var msg = "hello world";
console.log(msg.capit()); //"Hello World"
Copy after login

继承

利用[[Prototype]]特性,可以实现原型继承;对于字面量形式的对象,会隐式指定Object.prototype为其[[Prototype]],也可以通过Object.create()显示指定,其接受两个参数:第一个是[[Prototype]]指向的对象(原型对象),第二个是可选的属性描述符对象。

var book = {
title:"这是书名";
};
//和下面的方式一样
var book = Object.create(Object.prototype,{
title:{
configurable:true,
enumerable:true,
value:"这是书名",
wratable:true
}
});
Copy after login

字面量对象会默认继承自Object,更有趣的用法是,在自定义对象之间实现继承。

var book1 = {
title:"JS高级程序设计",
getTitle:function(){
console.log(this.title);
}
};
var book2 = Object.create(book1,{
title:{
configurable:true,
enumerable:true,
value:"JS权威指南",
wratable:true
}
});
book1.getTitle(); //"JS高级程序设计"
book2.getTitle(); //"JS权威指南"
console.log(book1.hasOwnProperty("getTitle")); //true
console.log(book1.isPrototypeOf("book2")); //false
console.log(book2.hasOwnProperty("getTitle")); //false
Copy after login

当访问book2的getTitle属性时,JavaScript引擎会执行一个搜索过程:现在book2的自有属性中寻找,找到则使用,若没有找到,则搜索[[Prototype]],若没有找到,则继续搜索原型对象的[[Prototype]],直到继承链末端。末端通常是Object.prototype,其[[Prototype]]被设置为null。


实现继承的另外一种方式是利用构造函数。每个函数都具有可写的prototype属性,默认被自懂设置为继承自Object.prototype,可以通过改写它来改变原型链。

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;
}
//修改prototype属性
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()); //50
console.log(square.getArea()); //36
Copy after login

如果要访问父类的toString(),可以这样做:

Square.prototype.toString = function(){
var text = Rect.prototype.toString.call(this);
return text.replace("Rect","Square");
}
Copy after login

更多JavaScript object-oriented essentials相关文章请关注PHP中文网!

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!