Home Web Front-end JS Tutorial Detailed explanation of JavaScript function definition, calling mode and initialization example of this

Detailed explanation of JavaScript function definition, calling mode and initialization example of this

Jul 25, 2017 am 10:43 AM
javascript js model

Function definition

Functions contain a set of statements, which are the basic module units of JavaScript and are used for code reuse, information hiding and combined calls. Functions are used to specify the behavior of objects

The four calling modes of functions and the initialization of this

The first: method calling mode
The following examples prove calling through the method calling mode , this is bound to the object that owns the method. For example:

var person = {
    name: "defaultName",
    setName : function(name){
        this.name = name;
    }
};
person.setName("zhangsan");
alert(person.name);
Copy after login

Second type: function call mode
The following example proves that when called through the function call mode, this is bound to the global object. Such as:

var test = add(value1, value2);
var name = "defaultName";
var person = {
    name: "zhangsan", // person中定义的name
    getName : function(){
        // 通过此方法可以将test函数的this改变为person的this对象
        var that = this;  // 解决方案
        // getName中定义的name
        var name = "lisi";
        var test = function(){
            // 通过that来访问person中的对象
            // this指向Global对象
            // this.name = defaultName
            // that.name = zhangsan
            alert([this.name, that.name]);
        };
        test(); // 函数调用模式
    }
}
person.getName();
Copy after login

Third: Constructor calling mode

// 定义一个Person的构造器,在调用时一定要用new调用
var Person = function(name){
    this.name = name;
}
// 添加一个方法到Person
Person.prototype.getName = function(){
    return this.name;
};
// 构造一个Person对象
var person = new Person("zhangsan");
alert(person.getName()); // 调用getName获取person对象中name属性的值
Copy after login

Fourth: Apply calling mode

<script type="text/javascript">
    // 定一个累加方法。如sum(1,2,3,4...)
    // 该方法位于window执行环境中。
    var displayName = function(){
        alert("sum的执行环境: " + typeof(this));
        alert("Name: " + this.name); // 取出当前执行环境中name属性
    }
    // 定一个Person对象
    var Person = {
        name: "zhangsan"
    };
    displayName.apply(Person);
</script>
Copy after login

The difference between Apply and call

// 定一个对象,包含一个add方法,返回a、b的和
var Person = {
    &#39;add&#39; : function(a, b){
        return a + b;
    }
};
// 显示a、b的和
function showInfo(a, b){
    alert(this.add(a, b));
}
// 通过apply方法改变showInfo方法的this指向
//showInfo(1, 3); // 对象不支持次对象
showInfo.apply(Person, [1, 3]);
showInfo.call(Person, 1, 3);
// 从上面可以看出,apply和call的区别是apply接受一个数组作为被调函数的参数,
// 而call是通过将被调函数的所有参数以逗号分隔的形式展开
Copy after login

The above is the detailed content of Detailed explanation of JavaScript function definition, calling mode and initialization example of this. 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)

What does WeChat's Do Not Disturb mode do? What does WeChat's Do Not Disturb mode do? Feb 23, 2024 pm 10:48 PM

What does WeChat Do Not Disturb mode mean? Nowadays, with the popularity of smartphones and the rapid development of mobile Internet, social media platforms have become an indispensable part of people's daily lives. WeChat is one of the most popular social media platforms in China, and almost everyone has a WeChat account. We can communicate with friends, family, and colleagues in real time through WeChat, share moments in our lives, and understand each other’s current situation. However, in this era, we are also inevitably faced with the problems of information overload and privacy leakage, especially for those who need to focus or

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

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Do Not Disturb Mode Not Working in iPhone: Fix Do Not Disturb Mode Not Working in iPhone: Fix Apr 24, 2024 pm 04:50 PM

Even answering calls in Do Not Disturb mode can be a very annoying experience. As the name suggests, Do Not Disturb mode turns off all incoming call notifications and alerts from emails, messages, etc. You can follow these solution sets to fix it. Fix 1 – Enable Focus Mode Enable focus mode on your phone. Step 1 – Swipe down from the top to access Control Center. Step 2 – Next, enable “Focus Mode” on your phone. Focus Mode enables Do Not Disturb mode on your phone. It won't cause any incoming call alerts to appear on your phone. Fix 2 – Change Focus Mode Settings If there are some issues in the focus mode settings, you should fix them. Step 1 – Open your iPhone settings window. Step 2 – Next, turn on the Focus mode settings

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

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

See all articles