Maison interface Web js tutoriel javascript原生一步步实现bind分析

javascript原生一步步实现bind分析

Nov 03, 2016 am 09:14 AM

bind

官方描述

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

使用介绍

由于javascript中作用域是由其运行时候所处的环境决定的,所以往往函数定义和实际运行的时候所处环境不一样,那么作用域也会发生相应的变化。

例如下面这个情况:

var id = 'window'; 
//定义一个函数,但是不立即执行 
var test = function(){ 
    console.log(this.id) 
} 
test() // window 
//把test作为参数传递 
var obj = { 
    id:'obj', 
    hehe:test 
} 
//此时test函数运行环境发生了改变 
obj.hehe() // 'obj' 
//为了避免这种情况,javascript里面有一个bind方法可以在函数运行之前就绑定其作用域,修改如下 
 
var id = 'window'; 
var test = function(){ 
    console.log(this.id) 
}.bind(window) 
var obj = { 
    id:'obj', 
    hehe:test 
} 
test() // window 
obj.hehe() // window
Copier après la connexion

上面介绍了bind方法的一个重要作用就是为一个函数绑定作用域,但是bind方法在低版本浏览器不兼容,这里我们可以手动实现一下。

拆分一下关键思路

因为bind方法不会立即执行函数,需要返回一个待执行的函数(这里用到闭包,可以返回一个函数)return function(){}

作用域绑定,这里可以使用apply或者call方法来实现 xx.call(yy)/xx.apply(yy)

参数传递,由于参数的不确定性,需要用apply传递数组(实例更明了)xx.apply(yy,[...Array...]),如果用call就不太方便了,因为call后面的参数需要一个个列出来

实现

有了上述的思路,大致的雏形已经明了了,代码应该也很容易实现

绑定作用域,绑定传参

Function.prototype.testBind = function(that){ 
    var _this = this, 
        /* 
        *由于参数的不确定性,统一用arguments来处理,这里的arguments只是一个类数组对象,有length属性 
        *可以用数组的slice方法转化成标准格式数组,除了作用域对象that以外, 
        *后面的所有参数都需要作为数组参数传递 
        *Array.prototype.slice.apply(arguments,[1])/Array.prototype.slice.call(arguments,1) 
        */ 
        slice = Array.prototype.slice, 
        args = slice.apply(arguments,[1]); 
    //返回函数     
    return function(){ 
        //apply绑定作用域,进行参数传递 
        return _this.apply(that,args) 
    }     
}
Copier après la connexion

测试

var test = function(a,b){ 
    console.log('作用域绑定 '+ this.value) 
    console.log('testBind参数传递 '+ a.value2) 
    console.log('调用参数传递 ' + b) 
} 
var obj = { 
    value:'ok' 
} 
var fun_new = test.testBind(obj,{value2:'also ok'}) 
 
fun_new ('hello bind') 
// 作用域绑定 ok 
// testBind参数传递 also ok 
// 调用参数传递  undefined
Copier après la connexion

动态参数

上面已经实现了bind方法的作用域绑定,但是美中不足的是,既然我们返回的是一个函数,调用的时候应该支持传递参数,很显然,上面的 fun_new 调用的时候并不支持传参,只能在 testBind 绑定的时候传递参数,因为我们最终调用的是这个返回函数

function(){ 
        return _this.apply(that,args) 
    }     
 
这里面的args在绑定的时候就已经确定了,调用的时候值已经固定, 
我们并没有处理这个function传递的参数。
Copier après la connexion

我们对其进行改造

return function(){ 
        return _this.apply(that, 
            args.concat(Array.prototype.slice.apply(arguments,[0])) 
        ) 
    }
Copier après la connexion

这里的 Array.prototype.slice.apply(arguments,[0]) 指的是这个返回函数执行的时候传递的一系列参数,所以是从第一个参数开始 [0] ,之前的args = slice.apply(arguments,[1])指的是 testBind方法执行时候传递的参数,所以从第二个开始 [1],两则有本质区别,不能搞混,只有两者合并了之后才是返回函数的完整参数

所以有如下实现

Function.prototype.testBind = function(that){ 
    var _this = this, 
        slice = Array.prototype.slice, 
        args = slice.apply(arguments,[1]); 
    return function(){ 
        return _this.apply(that, 
                    args.concat(Array.prototype.slice.apply(arguments,[0])) 
                ) 
    }     
}
Copier après la connexion

测试

var test = function(a,b){ 
    console.log('作用域绑定 '+ this.value) 
    console.log('testBind参数传递 '+ a.value2) 
    console.log('调用参数传递 ' + b) 
} 
var obj = { 
    value:'ok' 
} 
var fun_new = test.testBind(obj,{value2:'also ok'}) 
 
fun_new ('hello bind') 
// 作用域绑定 ok 
// testBind参数传递 also ok 
// 调用参数传递  hello bind
Copier après la connexion

在以上2种传参方式中,bind的优先级高,从 args.concat(Array.prototype.slice.apply(arguments,[0])) 也可以看出来,bind的参数在数组前面。

原型链

官方文档上有一句话:

A bound function may also be constructed using the new operator: doing

so acts as though the target function had instead been constructed.

The provided this value is ignored, while prepended arguments are

provided to the emulated function.

说明绑定过后的函数被new实例化之后,需要继承原函数的原型链方法,且绑定过程中提供的this被忽略(继承原函数的this对象),但是参数还是会使用。

这里就需要一个中转函数把原型链传递下去

fNOP = function () {} //创建一个中转函数 
fNOP.prototype = this.prototype; 
xx.prototype = new fNOP()  
修改如下 
Function.prototype.testBind = function(that){ 
    var _this = this, 
        slice = Array.prototype.slice, 
        args = slice.apply(arguments,[1]), 
        fNOP = function () {}, 
        //所以调用官方bind方法之后 有一个name属性值为 'bound ' 
        bound = function(){ 
            return _this.apply(that, 
                args.concat(Array.prototype.slice.apply(arguments,[0])) 
            ) 
        }     
 
    fNOP.prototype = _this.prototype; 
 
    bound.prototype = new fNOP(); 
 
    return bound; 
}
Copier après la connexion

而且bind方法的第一个参数this是可以不传的,需要分2种情况

直接调用bind之后的方法

var f = function () { console.log('不传默认为'+this)  };f.bind()() 
// 不传默认为 Window
Copier après la connexion

javascript原生一步步实现bind分析

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。

作者:谁谁来源:segmentfault|2016-11-02 18:54

收藏

分享



bind

官方描述

bind() 函数会创建一个新函数(称为绑定函数),新函数与被调函数(绑定函数的目标函数)具有相同的函数体(在 ECMAScript 5 规范中内置的call属性)。当目标函数被调用时 this 值绑定到 bind() 的第一个参数,该参数不能被重写。绑定函数被调用时,bind() 也接受预设的参数提供给原函数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

使用介绍

由于javascript中作用域是由其运行时候所处的环境决定的,所以往往函数定义和实际运行的时候所处环境不一样,那么作用域也会发生相应的变化。

例如下面这个情况:

var id = 'window'; 
//定义一个函数,但是不立即执行 
var test = function(){     
console.log(this.id) } 
test() 
// window 
//把test作为参数传递 
var obj = {     
id:'obj',     
hehe:test } 
//此时test函数运行环境发生了改变 obj.hehe() 
// 'obj' 
//为了避免这种情况,javascript里面有一个bind方法可以在函数运行之前就绑定其作用域,修改如下  
var id = 'window'; 
var test = function(){     
console.log(this.id) }.bind(window) 
var obj = {     
id:'obj',     
hehe:test } 
test() 
// window obj.hehe() 
// window
Copier après la connexion

上面介绍了bind方法的一个重要作用就是为一个函数绑定作用域,但是bind方法在低版本浏览器不兼容,这里我们可以手动实现一下。

拆分一下关键思路

因为bind方法不会立即执行函数,需要返回一个待执行的函数(这里用到闭包,可以返回一个函数)return function(){}

作用域绑定,这里可以使用apply或者call方法来实现 xx.call(yy)/xx.apply(yy)

参数传递,由于参数的不确定性,需要用apply传递数组(实例更明了)xx.apply(yy,[...Array...]),如果用call就不太方便了,因为call后面的参数需要一个个列出来

实现

有了上述的思路,大致的雏形已经明了了,代码应该也很容易实现

绑定作用域,绑定传参

Function.
prototype.
testBind = function(that){     
var _this = this,         
/*         
*由于参数的不确定性,统一用arguments来处理,这里的arguments只是一个类数组对象,有length属性         
*可以用数组的slice方法转化成标准格式数组,除了作用域对象that以外,         
*后面的所有参数都需要作为数组参数传递         
*Array.prototype.slice.apply(arguments,[1])/Array.prototype.slice.call(arguments,1)         
*/         
slice = Array.prototype.slice,         
args = slice.apply(arguments,[1]);     
//返回函数         
return function(){         
//apply绑定作用域,进行参数传递         
return _this.apply(that,args)     
}     
}
Copier après la connexion

测试

var test = function(a,b){     
console.log('作用域绑定 '+ this.value)     
console.log('testBind参数传递 '+ a.value2)     
console.log('调用参数传递 ' + b) 
} 
var obj = {     
value:'ok' } 
var fun_new = test.testBind(obj,{value2:'also ok'})  
fun_new ('hello bind') 
// 作用域绑定 ok 
// testBind参数传递 also ok 
// 调用参数传递  undefined
Copier après la connexion

动态参数

上面已经实现了bind方法的作用域绑定,但是美中不足的是,既然我们返回的是一个函数,调用的时候应该支持传递参数,很显然,上面的 fun_new 调用的时候并不支持传参,只能在 testBind 绑定的时候传递参数,因为我们最终调用的是这个返回函数

function(){         
return _this.apply(that,args)     
}      
这里面的args在绑定的时候就已经确定了,调用的时候值已经固定, 我们并没有处理这个function传递的参数。
Copier après la connexion

我们对其进行改造

return function(){         
return _this.apply(that,             
args.concat(Array.prototype.slice.apply(arguments,[0]))         
)    
}
Copier après la connexion


这里的 Array.prototype.slice.apply(arguments,[0]) 指的是这个返回函数执行的时候传递的一系列参数,所以是从第一个参数开始 [0] ,之前的args = slice.apply(arguments,[1])指的是 testBind方法执行时候传递的参数,所以从第二个开始 [1],两则有本质区别,不能搞混,只有两者合并了之后才是返回函数的完整参数

所以有如下实现

Function.
prototype.testBind = function(that){     
var _this = this,         
slice = Array.prototype.slice,         
args = slice.apply(arguments,[1]);     
return function(){         
return _this.apply(that,                     
args.concat(Array.prototype.slice.apply(arguments,[0]))                 
)     
}     
}
Copier après la connexion

测试

var test = function(a,b){     
console.log('作用域绑定 '+ this.value)     
console.log('testBind参数传递 '+ a.value2)     
console.log('调用参数传递 ' + b) } 
var obj = {     value:'ok' } 
var fun_new = test.testBind(obj,{value2:'also ok'})  
fun_new ('hello bind') 
// 作用域绑定 ok 
// testBind参数传递 also ok 
// 调用参数传递  hello bind
Copier après la connexion

在以上2种传参方式中,bind的优先级高,从 args.concat(Array.prototype.slice.apply(arguments,[0])) 也可以看出来,bind的参数在数组前面。

原型链

官方文档上有一句话:

A bound function may also be constructed using the new operator: doing

so acts as though the target function had instead been constructed.

The provided this value is ignored, while prepended arguments are

provided to the emulated function.

说明绑定过后的函数被new实例化之后,需要继承原函数的原型链方法,且绑定过程中提供的this被忽略(继承原函数的this对象),但是参数还是会使用。

这里就需要一个中转函数把原型链传递下去

fNOP = function () {} 
//创建一个中转函数 
fNOP.prototype = this.prototype; 
xx.prototype = new fNOP()  
修改如下 
Function.prototype.testBind = function(that){     
var _this = this,         
slice = Array.prototype.slice,         
args = slice.apply(arguments,[1]),         
fNOP = function () {},         
//所以调用官方bind方法之后 有一个name属性值为 'bound '         
bound = function(){             
return _this.apply(that,                 
args.concat(Array.prototype.slice.apply(arguments,[0]))             
)         
}          
fNOP.prototype = _this.prototype;      
bound.prototype = new fNOP();      
return bound; }
Copier après la connexion


而且bind方法的第一个参数this是可以不传的,需要分2种情况

直接调用bind之后的方法

var f = function () { console.log('不传默认为'+this)  };f.bind()() // 不传默认为 Window
Copier après la connexion

所以直接调用绑定方法时候 apply(that, 建议改为 apply(that||window,,其实不改也可以,因为不传默认指向window

使用new实例化被绑定的方法

容易糊涂,重点在于弄清楚标准的bind方法在new的时候做的事情,然后就可以清晰的实现

这里我们需要看看 new 这个方法做了哪些操作 比如说 var a = new b()

创建一个空对象 a = {},并且this变量引用指向到这个空对象a

继承被实例化函数的原型 :a.__proto__ = b.prototype

被实例化方法b的this对象的属性和方法将被加入到这个新的 this 引用的对象中: b的属性和方法被加入的 a里面

新创建的对象由 this 所引用 :b.call(a)

通过以上可以得知,如果是var after_new = new bindFun(); 由于这种行为是把原函数当成构造器,那么那么最终实例化之后的对象this需要继承自原函数, 而这里的 bindFun 目前是

function(){ 
            return _this.apply(that || window, 
                args.concat(Array.prototype.slice.apply(arguments,[0])) 
            ) 
        }
Copier après la connexion

这里apply的作用域是绑定的that || window,在执行 testBind()的时候就已经固定,并没有把原函数的this对象继承过来,不符合我们的要求,我们需要根据apply的特性解决这个问题:

在一个子构造函数中,你可以通过调用父构造函数的 `apply/call` 方法来实现继承

例如

function Product(name, price) { 
  this.name = name; 
  this.price = price; 
 
  if (price < 0) { 
    throw RangeError(&#39;Cannot create product &#39; + 
                      this.name + &#39; with a negative price&#39;); 
  } 
} 
 
function Food(name, price) { 
  Product.call(this, name, price);  
  this.category = &#39;food&#39;; 
} 
 
//等同于(其实就是把Product放在Food内部执行了一次) 
function Food(name, price) {  
    this.name = name; 
    this.price = price; 
    if (price < 0) { 
        throw RangeError(&#39;Cannot create product &#39; + 
                this.name + &#39; with a negative price&#39;); 
    } 
 
    this.category = &#39;food&#39;;  
}
Copier après la connexion

所以在new新的实例的时候实时将这个新的this对象 进行 apply 继承原函数的 this 对象,就可以达到 new 方法里面的第 3 步的结果

apply(that||window, 
//修改为 如果是new的情况,需要绑定new之后的作用域,this指向新的实例对象 
apply(isNew ? this : that||window,  ==> 
 
Function.prototype.testBind = function(that){ 
    var _this = this, 
        slice = Array.prototype.slice, 
        args = slice.apply(arguments,[1]), 
        fNOP = function () {}, 
        //所以调用官方bind方法之后 有一个name属性值为 &#39;bound &#39; 
        bound = function(){ 
            return _this.apply(isNew ? this : that||window, 
                args.concat(Array.prototype.slice.apply(arguments,[0])) 
            ) 
        }     
 
    fNOP.prototype = _this.prototype; 
 
    bound.prototype = new fNOP(); 
 
    return bound; 
}
Copier après la connexion

这里的 isNew 是区分 bindFun 是直接调用还是被 new 之后再调用,通过原型链的继承关系可以知道,

bindFun 属于 after_new的父类,所以 after_new instanceof bindFun 为 true,同时

bindFun.prototype = new fNOP() 原型继承; 所以 fNOP 也是 after_new的父类, after_new instanceof fNOP 为 true

最终结果

Function.prototype.testBind = function(that){ 
        var _this = this, 
            slice = Array.prototype.slice, 
            args = slice.apply(arguments,[1]), 
            fNOP = function () {}, 
            bound = function(){ 
                //这里的this指的是调用时候的环境 
                return _this.apply(this instanceof  fNOP ? this : that||window, 
                    args.concat(Array.prototype.slice.apply(arguments,[0])) 
                ) 
            }     
        fNOP.prototype = _this.prototype; 
     
        bound.prototype = new fNOP(); 
     
        return bound; 
    }
Copier après la connexion

我看到有些地方写的是

this instanceof fNOP && that ? this : that || window,
Copier après la connexion

我个人觉得这里有点不正确,如果绑定时候不传参数,那么that就为空,那无论怎样就只能绑定 window作用域了。

以上就是javascript原生一步步实现bind分析的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment mettre en œuvre un système de reconnaissance vocale en ligne à l'aide de WebSocket et JavaScript Comment mettre en œuvre un système de reconnaissance vocale en ligne à l'aide de WebSocket et JavaScript Dec 17, 2023 pm 02:54 PM

Comment utiliser WebSocket et JavaScript pour mettre en œuvre un système de reconnaissance vocale en ligne Introduction : Avec le développement continu de la technologie, la technologie de reconnaissance vocale est devenue une partie importante du domaine de l'intelligence artificielle. Le système de reconnaissance vocale en ligne basé sur WebSocket et JavaScript présente les caractéristiques d'une faible latence, d'un temps réel et d'une multiplateforme, et est devenu une solution largement utilisée. Cet article explique comment utiliser WebSocket et JavaScript pour implémenter un système de reconnaissance vocale en ligne.

WebSocket et JavaScript : technologies clés pour mettre en œuvre des systèmes de surveillance en temps réel WebSocket et JavaScript : technologies clés pour mettre en œuvre des systèmes de surveillance en temps réel Dec 17, 2023 pm 05:30 PM

WebSocket et JavaScript : technologies clés pour réaliser des systèmes de surveillance en temps réel Introduction : Avec le développement rapide de la technologie Internet, les systèmes de surveillance en temps réel ont été largement utilisés dans divers domaines. L'une des technologies clés pour réaliser une surveillance en temps réel est la combinaison de WebSocket et de JavaScript. Cet article présentera l'application de WebSocket et JavaScript dans les systèmes de surveillance en temps réel, donnera des exemples de code et expliquera leurs principes de mise en œuvre en détail. 1. Technologie WebSocket

Comment utiliser JavaScript et WebSocket pour mettre en œuvre un système de commande en ligne en temps réel Comment utiliser JavaScript et WebSocket pour mettre en œuvre un système de commande en ligne en temps réel Dec 17, 2023 pm 12:09 PM

Introduction à l'utilisation de JavaScript et de WebSocket pour mettre en œuvre un système de commande en ligne en temps réel : avec la popularité d'Internet et les progrès de la technologie, de plus en plus de restaurants ont commencé à proposer des services de commande en ligne. Afin de mettre en œuvre un système de commande en ligne en temps réel, nous pouvons utiliser les technologies JavaScript et WebSocket. WebSocket est un protocole de communication full-duplex basé sur le protocole TCP, qui peut réaliser une communication bidirectionnelle en temps réel entre le client et le serveur. Dans le système de commande en ligne en temps réel, lorsque l'utilisateur sélectionne des plats et passe une commande

Comment mettre en œuvre un système de réservation en ligne à l'aide de WebSocket et JavaScript Comment mettre en œuvre un système de réservation en ligne à l'aide de WebSocket et JavaScript Dec 17, 2023 am 09:39 AM

Comment utiliser WebSocket et JavaScript pour mettre en œuvre un système de réservation en ligne. À l'ère numérique d'aujourd'hui, de plus en plus d'entreprises et de services doivent fournir des fonctions de réservation en ligne. Il est crucial de mettre en place un système de réservation en ligne efficace et en temps réel. Cet article explique comment utiliser WebSocket et JavaScript pour implémenter un système de réservation en ligne et fournit des exemples de code spécifiques. 1. Qu'est-ce que WebSocket ? WebSocket est une méthode full-duplex sur une seule connexion TCP.

JavaScript et WebSocket : créer un système efficace de prévisions météorologiques en temps réel JavaScript et WebSocket : créer un système efficace de prévisions météorologiques en temps réel Dec 17, 2023 pm 05:13 PM

JavaScript et WebSocket : Construire un système efficace de prévisions météorologiques en temps réel Introduction : Aujourd'hui, la précision des prévisions météorologiques revêt une grande importance pour la vie quotidienne et la prise de décision. À mesure que la technologie évolue, nous pouvons fournir des prévisions météorologiques plus précises et plus fiables en obtenant des données météorologiques en temps réel. Dans cet article, nous apprendrons comment utiliser la technologie JavaScript et WebSocket pour créer un système efficace de prévisions météorologiques en temps réel. Cet article démontrera le processus de mise en œuvre à travers des exemples de code spécifiques. Nous

Tutoriel JavaScript simple : Comment obtenir le code d'état HTTP Tutoriel JavaScript simple : Comment obtenir le code d'état HTTP Jan 05, 2024 pm 06:08 PM

Tutoriel JavaScript : Comment obtenir le code d'état HTTP, des exemples de code spécifiques sont requis Préface : Dans le développement Web, l'interaction des données avec le serveur est souvent impliquée. Lors de la communication avec le serveur, nous devons souvent obtenir le code d'état HTTP renvoyé pour déterminer si l'opération a réussi et effectuer le traitement correspondant en fonction de différents codes d'état. Cet article vous apprendra comment utiliser JavaScript pour obtenir des codes d'état HTTP et fournira quelques exemples de codes pratiques. Utilisation de XMLHttpRequest

Comment utiliser insertBefore en javascript Comment utiliser insertBefore en javascript Nov 24, 2023 am 11:56 AM

Utilisation : En JavaScript, la méthode insertBefore() est utilisée pour insérer un nouveau nœud dans l'arborescence DOM. Cette méthode nécessite deux paramètres : le nouveau nœud à insérer et le nœud de référence (c'est-à-dire le nœud où le nouveau nœud sera inséré).

Comment obtenir facilement le code d'état HTTP en JavaScript Comment obtenir facilement le code d'état HTTP en JavaScript Jan 05, 2024 pm 01:37 PM

Introduction à la méthode d'obtention du code d'état HTTP en JavaScript : Dans le développement front-end, nous devons souvent gérer l'interaction avec l'interface back-end, et le code d'état HTTP en est une partie très importante. Comprendre et obtenir les codes d'état HTTP nous aide à mieux gérer les données renvoyées par l'interface. Cet article explique comment utiliser JavaScript pour obtenir des codes d'état HTTP et fournit des exemples de code spécifiques. 1. Qu'est-ce que le code d'état HTTP ? Le code d'état HTTP signifie que lorsque le navigateur lance une requête au serveur, le service

See all articles