Home Web Front-end JS Tutorial Comprehensive analysis of Object type and scope in JavaScript object-oriented concepts (with examples)

Comprehensive analysis of Object type and scope in JavaScript object-oriented concepts (with examples)

May 21, 2018 pm 02:50 PM
javascript js object

This article mainly introduces the reference type and scope in parsing JavaScript object-oriented concepts. The article focuses on the call and apply methods needed to expand the running scope of functions. Friends can refer to it

Reference type

Reference types mainly include: Object type, Array type, Date type, RegExp type, Function type, etc.

When reference types are used, an object (instance) needs to be generated from them. In other words, the reference type is equivalent to a template. When we want to use a certain reference type, we need to use this template to generate an object for use, so the reference type is sometimes called an object definition.

For example, if we need to generate a person object to define someone's personal information and behavior, then we need to rely on the Object type:

var person = new Object();
person.name = "jiangshui";
person.sayName = function(){
  console.log(this.name);
}
Copy after login

The person object above is defined using the "template" of the Object type through the new operator. Then you can add the attribute name and method sayName to this object. Properties and methods are "features" of the Object type, so objects created through reference types such as Object can use this.

Creating an object does not necessarily require using the new operator. There are some types that can be simplified to create. For example, to create an object of type Object as above, you can also use the following two methods:

var person = {};
person.name = "jiangshui";
person.sayName = function(){
  console.log(this.name);
}
Copy after login

or

var person = {
  name : "jiangshui",
  sayName : function(){
    console.log(this.name);
  }
};
Copy after login
Copy after login

{} operator has the same function as new Object(), simplifying the operation . There are some differences between the above two ways of writing. The first one is "append", that is, continue to add attributes or methods to the previous definition. If an attribute method with the same name already exists, it will be overwritten. The second type is "replacement", which means that regardless of whether the attributes and methods of the person object are previously defined, this method will completely replace the previously defined ones with the newly defined content. Because the object generated by the reference type is stored in an area in memory, and then its pointer is stored in a variable (person), the second way of writing is to generate a new object (new memory area), and then save the person variable Points to the new memory area, so the previous one is replaced. Understanding this is crucial to understanding later.

The usage of other reference types is roughly the same, such as the Array type. You can also use [] to generate objects, or define them directly. After the array object is generated, the information content can be stored in the array format. In addition, the object will get the methods defined in the Array type, such as push, shift, sort, etc., and these methods can be called, for example:

var colors = [];
colors.push('red','green');
console.log(colors);
Copy after login

The above code creates an array type object through the Array type, then calls the push method defined previously in the Array type, and adds red and green values ​​​​to the object. Finally Print it on the console and you can see it.

call and apply methods

These two methods are provided by the Function type, that is to say, they can be used on functions. The call and apply methods have the same function, that is, they can expand the scope of function operation. The difference is that when using call, the parameters passed to the function must be listed one by one, but the apply method does not. In this way, you can decide to use call or apply according to the requirements of your own function.

What does it mean to extend the scope in which a function runs? Give an example and you will understand.

You can understand it this way, the function is wrapped in a container (scope), and there are some variables or other things in this container. When the function runs, calls these variables, etc., it will be found in the current container. this thing. This container is actually wrapped in a larger container. If the current small container does not exist, the function will search for it in the larger container, and so on, until it finds the largest container window object. But if the function is running in the current small container and there are corresponding variables in the small container, even in the large container, the function will still call the variables in its own container.

The call and apply methods are to solve this problem and break through the limitations of the container. Just take the previous example:

var person = {
  name : "jiangshui",
  sayName : function(){
    console.log(this.name);
  }
};
Copy after login
Copy after login

After opening Chrome’s Console, paste it in and execute it, and then execute person.sayName() to see

2016510174813378.png (926×572)

At this time, person is a container, in which a sayName method (function) is created. When executed, it must be executed under the person scope. When executed directly at the bottom, that is, executed under the scope of window, an error not defined will be reported because the sayName method is not defined under window. The this pointer inside is a special thing. It points to the current scope. The meaning of this.name is to call the name value under the current scope.

Next we add a name attribute to the window object:

window.name = "yujiangshui";
Copy after login

or directly

name = "yujiangshui";
Copy after login

因为 window 是最大的容器,所以 window 可以省略掉,所有定义的属性或者变量,都挂靠到 window 上面去了,不信可以看:

2016510174850232.png (486×412)

那现在我们就想在 window 这个大容器下面,运行 person 小容器里面的 sayName 方法,就需要用 call 或 apply 来扩充 sayName 方法的作用域。执行下面语句:

person.sayName.call(window);
Copy after login

或者

person.sayName.call(this);
Copy after login

输出的结果都是一样的,你也可以换用 apply 看看效果,因为这个 demo 太简单的,不需要传递参数,所以 call 和 apply 功能效果就完全一致了。

2016510174922644.png (438×360)

解释一下上面代码,sayName 首先是 Function 类型的实例,也就具有了 call 方法和 apply 方法,call 和 apply 方法既然是 Function 类型的方法,所以就需要用这种方式调用 person.sayName.call(window) 而不是什么 person.sayName().call(window) 之类的。

然后 call 和 apply 方法的参数,就是一个作用域(对象),表示将前面的函数在传递进去的作用域下面运行。将 window 这对象传递进去之后,sayName 方法中的 this.name 指向的就是 window.name,于是就扩充了作用域。

为什么传递 window 和 this 都是一样的效果?因为我们当前执行这个函数的位置是 window,前面说过 this 指针指向的是当前作用域,所以 this 指向的就是 window,所以就等于 window。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在javascript中创建对象的各种模式解析(图文教程)

设计模式中的组合模式在JavaScript程序构建中的使用(高级篇)

详细解读JavaScript设计模式开发中的桥接模式(高级篇)

The above is the detailed content of Comprehensive analysis of Object type and scope in JavaScript object-oriented concepts (with examples). 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 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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

See all articles