将函数直接链接到Javascript中新创建的对象实例
在我正在进行的深入了解面向对象Javascript的故事中,我遇到了一个关于创建一个类来响应以下API的问题:将函数直接链接到Javascript中新创建的对象实例,javascript,Javascript,在我正在进行的深入了解面向对象Javascript的故事中,我遇到了一个关于创建一个类来响应以下API的问题: var foo = new bar().delay(750).start().then(onComplete); var bar = function() { this.delay(function(per) { //... }; } 能不能请一个比我更有经验的人描述一下如何创建一个能够响应这个问题的类?我从未见过这样的链接,也无法在网上找到任何信息:(
var foo = new bar().delay(750).start().then(onComplete);
var bar = function() {
this.delay(function(per) {
//...
};
}
能不能请一个比我更有经验的人描述一下如何创建一个能够响应这个问题的类?我从未见过这样的链接,也无法在网上找到任何信息:(此链接通过在函数中返回
this
来完成:
this.delay = function(per) {
//...
return this;
};
如果您想坚持使用第一行代码,那么您的构造函数应命名为bar:
var bar = function() {
this.delay = function(per) {
//...
return this;
};
this.start = function() {
...
return this;
};
}
请参阅(打开控制台)此链接通过在函数中返回
This
来完成:
this.delay = function(per) {
//...
return this;
};
如果您想坚持使用第一行代码,那么您的构造函数应命名为bar:
var bar = function() {
this.delay = function(per) {
//...
return this;
};
this.start = function() {
...
return this;
};
}
请参阅(打开控制台)方法链接的秘诀是从您希望能够链接的每个方法返回
this
。这允许下一个方法自动成为this.method()
。您对bar对象的定义类似于此shell:
function bar() {
// bar initialization code here
}
bar.prototype = {
delay: function(amt) {
// delay code here
return(this);
},
start: function() {
// start code here
return(this);
},
then: function(fn) {
// then code here
fn();
return(this);
}
};
var foo = new bar().delay(750).start().then(onComplete);
在您的示例中,执行newbar()
,并返回指向新bar
对象的指针。
使用新的对象指针,对该对象调用
.delay(750)
方法。然后该方法还返回该对象,因此对.delay(750)的返回值调用.start()
方法
仍然是相同的对象,等等…方法链接的秘密是从您希望能够链接的每个方法返回此
。这允许下一个方法自动成为此.method()
。您对bar对象的定义类似于此shell:
function bar() {
// bar initialization code here
}
bar.prototype = {
delay: function(amt) {
// delay code here
return(this);
},
start: function() {
// start code here
return(this);
},
then: function(fn) {
// then code here
fn();
return(this);
}
};
var foo = new bar().delay(750).start().then(onComplete);
在您的示例中,执行newbar()
,并返回指向新bar
对象的指针。
使用新的对象指针,对该对象调用.delay(750)
方法。然后,该方法还返回该对象,因此对.start()
返回值调用.delay(750)
方法,该返回值仍然是相同的对象,依此类推……这是通过调用的。这是通过调用的。