Home Web Front-end JS Tutorial A brief introduction to object-oriented and Object types in js (with code)

A brief introduction to object-oriented and Object types in js (with code)

Aug 15, 2018 pm 01:42 PM
javascript

This article brings you a brief introduction to object-oriented and Object types in js (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Object-oriented

The full name of object-oriented programming is Object Oriented Programming, or OOP for short. Object-oriented programming is a programming method that uses abstract methods to create models based on the real world.
Object-oriented programming can be seen as software design that uses a series of objects to cooperate with each other. The three main characteristics of object-oriented programming are: encapsulation, inheritance, and polymorphism.

Encapsulation

The so-called encapsulation is to use it according to the requirements and get the corresponding results without knowing the real execution principle.
Encapsulation is mainly used to describe the (encapsulated) content contained in the object. It usually consists of two parts

  • Related data (used to store attributes)

  • What can be done based on this data

Inheritance Inheritance usually refers to the relationship between classes. If two classes have the same properties or methods, then one class can inherit the other class without having to define the same properties or methods again.
Creating a specialized version of one or more classes is called inheritance (JavaScript only supports single inheritance). The specialized version of a class that is created is usually called a subclass, and the additional class is usually called a parent class.

Polymorphism

Different objects can define methods with the same name, and the methods act on the object where they are located. The ability of different objects to implement their own behaviors through the same method call is called polymorphism.

Constructor

The constructor, also known as the constructor or object template, is a method of the object. The constructor is called during instantiation. Functions can be used as constructors in JavaScript.

/*  创建构造函数->用于创建对象
*    function 构造函数名称(){
*       this.属性名 = 属性值
*       this.方法名 = function(){
*           方法体
*           }
*     }
      this关键字指代利用当前构造函数创建的对象*/
function Dog() {//这是构造函数,构造函数的属性和方法使用this关键字
    this.name=function () {
        console.log('哈士奇')
    }
}

/*   利用构造函数创建对象*/
var dog = new Dog();
console.log(dog);
Copy after login

Object type

Property descriptor

JavaScript provides an internal data structure that describes the value of an object and controls its behavior, such as Whether the property is writable, configurable, deletable, enumerable, etc. This internal data structure is called a property descriptor.
There are two main forms of attribute descriptors currently existing in objects: data descriptors and access descriptors.

Data descriptor

A data descriptor is a property with a value that may be writable or unwritable. The data descriptor has the following optional key values:

  • value: The value corresponding to this attribute. Can be any valid JavaScript value. The default is undefined,

  • writable: If and only if the writable of the attribute is true, the value can be changed by the assignment operator. Default is false.

  • configurable: If and only if the configurable of the attribute is true, the attribute descriptor can be changed, and the attribute can also be deleted from the corresponding object. Default is false.

  • enumerable: If and only if the enumerable of the property is true, the property can appear in the enumeration property of the object. The default is false.

Access descriptor

Access descriptor is a property described by a getter-setter function pair. There are the following optional key values ​​

  • get: Provide a getter method for the property, if there is no getter, it will be undefined. When this property is accessed, the method will be executed. No parameters are passed in when the method is executed, but the this object will be passed in.

  • set: Provides a setter method for the property. If there is no setter, it will be undefined. This method is triggered when the property is modified. This method accepts the only parameter, which is the new parameter value of the changed attribute.

  • configurable: If and only if the configurable of the attribute is true, the attribute descriptor can be changed, and the attribute can also be deleted from the corresponding object. Default is false.

  • enumerable: If and only if the enumerable of the property is true, the property can appear in the enumeration property of the object. The default is false.

Get the property descriptor

The Object.getOwnPropentyDescriptor() method returns the property descriptor corresponding to the own property on the specified object

var obj = {
    name : '哈士奇'
}
/*
    使用Object.getOwnPropertyDescriptor()方法获取指定属性的描述符
    Object.getOwnPropertyDescriptor(obj,prop)
    * obj - 表示指定属性对应的目标对象
    * prop - 表示获取描述符的目标属性名称
    * 返回值 - 其属性描述符对象
    * 如果
  */
var v =Object.getOwnPropertyDescriptor(obj,'name');
console.log(v)
Copy after login

Set the property Descriptor optional key value value

  • The Object.deginepropety() method defines new properties for the object or modifies existing properties, and returns the object.

var obj ={//定义对象时定义的属性是可以修改、删除、枚举的
    name : '阿拉斯加'
}
/*
    Object.defineProperty(obj, prop, descriptor)方法
    * 作用
      * 用于定义目标对象的新属性
      * 用于修改目标对象的已存在属性
    * 参数
      * obj - 表示目标对象
      * prop - 表示目标对象的目标属性名称
      * descriptor - 表示属性描述符,必须是对象格式
        {
            value : 值
        }
    * 返回值 - 返回传递的对象
 */
//修改name属性
Object.defineProperty(obj, 'name',{
    value:'哈士奇'
} );
console.log(obj.name);//哈士奇

/*
    同样都是为对象新增属性
    1.如果直接使用 "对象名.属性名 = 值" -> 可修改、可删除以及可枚举的
    2.如果使用Object.defineProperty()方法新增属性
      * 该新属性是不可修改、不可删除以及不可枚举的
 */
//新增age属性//用该方法新增的属性默认是不可以修改、删除、枚举的
Object.defineProperty(obj,'age',{
    value : 2
});
Copy after login
  • The Object.degineproperties() method defines one or more new properties or modifies existing properties for the object and returns the value.

Set the attribute descriptor optional key value weitable

var obj = {
    // 定义对象的同时定义了该属性以及值(可修改、可删除以及可枚举的)
    name : '张无忌'
}
// 修改现有属性
Object.defineProperty(obj, 'name', {
    value : '周芷若',
    writable : false // 不可修改
});
console.log(obj.name);// 周芷若
// 修改name属性值
obj.name = '赵敏';
console.log(obj.name);// 周芷若

Object.defineProperty(obj, 'age', {
   value : 18,
   writable : true
});
console.log(obj.age);// 18
// 修改age属性值
obj.age = 80;
console.log(obj.age);// 80
Copy after login

Set the attribute descriptor optional key value configuarble

var obj = {
    // 定义对象的同时定义了该属性以及值(可修改、可删除以及可枚举的)
    name : '张无忌'
}
// 修改现有属性
Object.defineProperty(obj, 'name', {
    value : '周芷若',
    writable : true, // 控制当前属性是否可被修改
    configurable : true // 控制当前属性是否可被删除
});
console.log(obj.name);// 周芷若
// 修改name属性值
obj.name = '赵敏';
console.log(obj.name);// 赵敏
// 删除name属性值
delete obj.name;undefined
console.log(obj.name);// undefined
Copy after login

Set the attribute descriptor enumerable

var obj = {
    // 定义对象的同时定义了该属性以及值(可修改、可删除以及可枚举的)
    name : '张无忌'
}
Object.defineProperty(obj, 'name', {
    value : '周芷若',
    enumerable : false
});
console.log(obj.name);// 周芷若
/*
    属性描述符enumerable - 控制当前属性是否可被枚举(遍历)
    * 仅能循环遍历对象中可被枚举的属性
      * for...in语句
      * keys()方法
    * 可以循环遍历对象中可被枚举和不可被枚举的属性
      * getOwnPropertyNames()方法
 */
for (var i in obj) {
    console.log(i);
}
var result1 = Object.keys(obj);
console.log(result1);
var result2 = Object.getOwnPropertyNames(obj);
console.log(result2);
Copy after login

Set property descriptor accessor

In addition to being directly defined, the properties in the object can also be defined using accessors. The setter is a value function, using the set in the attribute descriptor; the getter is a value function, using the get in the attribute descriptor.

var value;
var obj = {
    // 存取描述符中的get
    get attr() {// 表示当前目标属性名称
        return value;
    },
    // 存取描述符中的set
    set attr(newValue) {// 表示当前目标属性名称
        console.log('setter: ' + newValue);
        value = newValue;
    }
}
console.log(obj.attr);// undefined
obj.attr = 100;// "setter: 100"
Copy after login

Tamper-proof object

The defined object can be modified at any time and anywhere by default, so a mechanism to prevent tampering is added and divided into three levels

  • Prohibit expansion: Prohibit the expansion of new properties and methods for objects

  • Sealed object: Only the value of the property is allowed to be read and written

  • Frozen object: No operations are allowed

Forbidden Extension

  • Object.preventExtensions() sets the specified object to be non-extensible

  • Object.isExtensible() determines whether an object can be extended

Sealing Object

  • Objet.seal() method is used to seal an object, prevent new properties from being added and mark existing properties as non-configurable, current properties The value can be written.

  • Object.Sealead() determines whether the object is sealed

Freeze Object

  • Object. freeze() is used to freeze an object. No operations can be performed on this object. It can only be read.

  • Object.isFrozen() determines whether the object is frozen

Related recommendations:

Javascript Object-oriented Object (Object)_js Object-oriented

How to use the prototype of the Object object in JS

#JavaScript object-oriented - simple object creation and JSON objects

The above is the detailed content of A brief introduction to object-oriented and Object types in js (with code). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles