您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

什么是装饰器以及它们在 JavaScript 中如何使用?

2024/4/22 13:35:05发布17次查看
在本教程中,您将了解 javascript 装饰器并了解它们的内部工作原理和用途。
javascript 中的装饰器是什么?装饰器这个词意味着将一组代码或程序与另一组代码或程序组合起来,或者可以说是用另一个函数包装一个函数以扩展该函数的功能或工作。装饰器也可以称为装饰器函数。
开发人员一直在 python、c# 等其他语言中使用这个装饰器术语,现在 javascript 也引入了装饰器。
函数装饰器在 javascript 中,函数的行为类似于对象,因此它们也被称为一等对象,发生这种情况是因为我们可以将函数分配给变量或从函数返回函数,或者可以将函数作为参数传递给函数.
示例const func_variable= function(){ console.log(hey there);}func_variable()
示例将函数传递给另一个函数
// mainfunction function takes a function as a parameterfunction mainfunction(func) { func() console.log(main function)}// assigning function to a variablevar argumentfunction = function() { console.log(passed function)}//passing argumentfunction function to to mainfunctionmainfunction(argumentfunction)
示例通过另一个函数返回一个函数
function sumelement(par1, par2) { var addnumbers = function () { result = par1+par2; console.log(sum is:, result); } // returns the addnumbers function return addnumbers}var printelement = sumelement(3, 4)console.log(printelement);printelement()
高阶函数高阶函数是指以函数作为参数并在执行某些操作后返回该函数的函数。上面讨论的函数是一个高阶函数,即printadditionfunc。
示例// higher order function function printname(name) { return function () { console.log(my name is , name); } } // output1 is a function, printname returns a functionvar output1 = printname(kalyan)output1()var output2= printname(ashish)output2()
你可能会想,我们已经有了装饰器作为高阶函数,那么为什么我们还需要单独的装饰器呢?
所以,我们有函数装饰器,它是一个高阶 javascript 函数,但是当类出现在 javascript 中时,我们在类中也有函数,其中高阶函数变得失败,就像装饰器一样。
示例让我们看看类的高阶函数的问题 -
// higher is a decorator functionfunction higher(arg) { return function() { console.log(first + arg.name) arg() // decorator function call console.log(last + arg.name) }}class website { constructor(fname, lname) { this.fname = fname this.lname = lname } websitename() { return this.fname + + this.lname }}var ob1 = new website(tutorials, point)// passing the class method websitename to the higher order functionvar printname = higher(ob1.websitename)printname()
这里发生的情况是,当调用更高的函数时,它会调用其参数,该参数是类的成员函数,作为此处的 websitename 函数。由于函数 websitename 是从外部类函数调用的,因此该函数的值在 websitename 函数内部未定义。因此,这就是此日志错误背后的原因。
因此,为了解决这个问题,我们还将传递 website 类的对象,该对象最终将保留 this 的值。
//higher is a decorator functionfunction higher(ob1, arg) { return function() { console.log(execution of + arg.name + begin) arg.call(ob1) //// decorator function call console.log(execution of + arg.name + end) }}class website { constructor(fname, lname) { this.fname = fname this.lname = lname } websitename() { return this.fname + + this.lname }}var ob1 = new website(tutorials, point)//passing the class method websitename to the higher order functionvar printname = higher(ob1, ob1.websitename)printname()
在 printname 函数中,我们通过 call 函数调用 arg (这是一个 websitename 函数),该函数通过 website 类对象的帮助调用 websitename 函数,因此该指针的值将是 website 类的对象,并且是具有 fname 和 lname 这两个变量,因此它将正常工作而不会出现任何错误。
希望您通过本文的帮助了解装饰器及其用途。
以上就是什么是装饰器以及它们在 javascript 中如何使用?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product