如果我有伪代码,如:
function user(a,b)
{
if(! (this instanceof user) ) return new user(a,b);
this.a = a;
this.b = b;
this.showName = function() {
alert(this.a + " " + this.b);
};
this.changeName = function(a,b) {
this.a = a;
this.b = b;
};
}
我可以这样称呼:
user("John", "Smith").showName() // output : John Smith
我想要类似的东西:
user("John", "Smith").changeName("Adam", "Smith").showName();
答案 0 :(得分:7)
在每个方法中返回对象。这被称为“链接”。
function user(a,b)
{
if(! (this instanceof user) ) return new user(a,b);
this.a = a;
this.b = b;
this.showName = function() {
alert(this.a + " " + this.b);
return this; // <--- returning this
};
this.changeName = function(a,b) {
this.a = a;
this.b = b;
return this; // <--- returning this
};
}