用带参数的new替换旧函数(replace old function with new with arguments)

编程入门 行业动态 更新时间:2024-10-20 16:02:45
用带参数的new替换旧函数(replace old function with new with arguments)

我有变量和函数的对象......以及新“function2”的定义

var object = { x: 11, y: 22, getX: function() { return this.x; } }; var function2 = function(value) { return value; };

我想替换旧的getX函数的定义:

object.getX = function2(arg);

但是这段代码不是替换功能,而是设置新值

怎么做?

当我调用object.getX(“aa”)时,当我调用object.getX(15).... value“aa”时,我想要值“15”

I have object with variables and functions ... and definition of new "function2"

var object = { x: 11, y: 22, getX: function() { return this.x; } }; var function2 = function(value) { return value; };

I want to replace definition of old getX function:

object.getX = function2(arg);

but this code is not replacing function, but setting new value

how to make it ?

I want value "15" when I call object.getX(15) .... value "aa" when I call object.getX("aa")

最满意答案

你必须为此目的使用bind(context,arguments..) ,

object.getX = function2.bind(object, arg);

如果您只是想在不设置任何上下文的情况下替换该function ( this ),

然后你可以简单地做到。

object.getX = function2;

你的完整代码是,

var object = { x: 11, y: 22, getX: function() { return this.x; } }; var function2 = function(value) { return value; }; object.getX = function2.bind(object); console.log(object.getX("aa")); //"aa"

You have to use bind(context,arguments..) for this purpose,

object.getX = function2.bind(object, arg);

And if you just want to replace the function without setting any context(this),

Then you can do it simply by.

object.getX = function2;

Your full code would be,

var object = { x: 11, y: 22, getX: function() { return this.x; } }; var function2 = function(value) { return value; }; object.getX = function2.bind(object); console.log(object.getX("aa")); //"aa"

更多推荐

本文发布于:2023-08-07 19:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   replace   function   arguments

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!