首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Currying函数构造函数

Currying函数构造函数
EN

Stack Overflow用户
提问于 2018-02-11 02:54:07
回答 3查看 484关注 0票数 2

我想知道在javascript中是否有可能做到这一点:

代码语言:javascript
复制
function Hello() { }

Hello.prototype.echo = function echo() {
  return 'Hello ' + this.firstname + '!';
};

// execute the curryed new function
console.log(new Hello()('firstname').echo())

有没有可能做var o = new Class()(param1)(param2)(...)

提前感谢您的帮助。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-02-11 03:47:09

georganswer与属性数组和用于分配任意数量属性的计数器一起使用。

代码语言:javascript
复制
function Hello() {
    var args = ['firstname', 'lastname'],
        counter = 0,
        self = function (val) {
            self[args[counter++]] = val;
            return self;
        };
    Object.setPrototypeOf(self, Hello.prototype);
    return self;
}

Hello.prototype.echo = function echo() {
    return 'Hello ' + this.firstname + ' ' + (this.lastname || '') + '!';
};

console.log(new Hello()('Bob').echo());
console.log(new Hello()('Marie')('Curie').echo());

票数 2
EN

Stack Overflow用户

发布于 2018-02-11 03:19:06

例如:

代码语言:javascript
复制
function Hello() {
    let self = function (key, val) {
        self[key] = val;
        return self;
    };
    Object.setPrototypeOf(self, Hello.prototype);
    return self;
}

Hello.prototype.echo = function echo() {
    return 'Hello ' + this.firstname + this.punct;
};

console.log(new Hello()('firstname', 'Bob')('punct', '...').echo())

票数 2
EN

Stack Overflow用户

发布于 2018-02-11 02:58:41

在您的代码中,new Hello('Bob')返回的不是函数,而是一个具有.echo()方法的对象。

当用new实例化时,function Hello(firstname) {}是一个返回对象的构造函数。

代码语言:javascript
复制
// constructor function expecting 1 argument
function Hello(firstname) {
  this.firstname = firstname;
}

// attach a method to the constructor prototype
Hello.prototype.echo = function() {
  return 'Hello ' + this.firstname + '!'; // the method can use the contructor's properties
};

// new Hello('Bob') returns the object, and you can call the .echo() method of that object
console.log(new Hello('Bob').echo())

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48724422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档