我想知道在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)(...)?
提前感谢您的帮助。
发布于 2018-02-11 03:47:09
将georg的answer与属性数组和用于分配任意数量属性的计数器一起使用。
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());
发布于 2018-02-11 03:19:06
例如:
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())
发布于 2018-02-11 02:58:41
在您的代码中,new Hello('Bob')返回的不是函数,而是一个具有.echo()方法的对象。
当用new实例化时,function Hello(firstname) {}是一个返回对象的构造函数。
// 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())
https://stackoverflow.com/questions/48724422
复制相似问题