Javascript 如何向函数添加方法?
具体来说,我如何编写允许链接的原型,例如:Javascript 如何向函数添加方法?,javascript,Javascript,具体来说,我如何编写允许链接的原型,例如: $('myDiv').html('Hello World').fadeIn('slow'); 您描述的技术被调用,它涉及从所有可链接函数返回相同类型的对象。该对象的原型包含函数定义 链接文章包括各种语言的示例代码,包括javascript。您描述的技术被调用,它涉及从所有可链接函数返回相同类型的对象。该对象的原型包含函数定义 链接文章包括各种语言的示例代码,包括javascript。只需从函数中返回适当的内容即可。基本的经验法则是采用任何正常情况下不
$('myDiv').html('Hello World').fadeIn('slow');
您描述的技术被调用,它涉及从所有可链接函数返回相同类型的对象。该对象的原型包含函数定义
链接文章包括各种语言的示例代码,包括javascript。您描述的技术被调用,它涉及从所有可链接函数返回相同类型的对象。该对象的原型包含函数定义
链接文章包括各种语言的示例代码,包括javascript。只需从函数中返回适当的内容即可。基本的经验法则是采用任何正常情况下不返回任何内容的方法,并使其返回
this
function Constructor(){};
Constructor.prototype = {
foo: function(){
console.log('foo');
return this;
},
bar: function(x){
console.log('bar', x);
return this;
}
}
var obj = new Constructor();
obj.foo().bar(17).bar(42).foo();
只需从函数中返回适当的内容。基本的经验法则是采用任何正常情况下不返回任何内容的方法,并使其返回
this
function Constructor(){};
Constructor.prototype = {
foo: function(){
console.log('foo');
return this;
},
bar: function(x){
console.log('bar', x);
return this;
}
}
var obj = new Constructor();
obj.foo().bar(17).bar(42).foo();
在这种特定情况下,每个方法都返回this。因此:
// ... this has to be the most impractical class I've ever written, but it is a
// great illustration of the point.
var returner = new function() {
this.returnThis = function(){
console.log("returning");
return this
}
}
var ret2 = returner.returnThis().returnThis().
returnThis().returnThis() // logs "returning" four times.
console.log( ret2 == returner ) // true
在这种特定情况下,每个方法都返回this。因此:
// ... this has to be the most impractical class I've ever written, but it is a
// great illustration of the point.
var returner = new function() {
this.returnThis = function(){
console.log("returning");
return this
}
}
var ret2 = returner.returnThis().returnThis().
returnThis().returnThis() // logs "returning" four times.
console.log( ret2 == returner ) // true
链接示例:
var avatar = function() {
this.turnLeft = function {
// some logic here
return this;
}
this.turnRight = function {
// some logic here
return this;
}
this.pickUpItem = function {
// some logic here
return this;
}
};
var frodo = new avatar();
frodo.turnLeft().turnRight().pickUpItem();
链接示例:
var avatar = function() {
this.turnLeft = function {
// some logic here
return this;
}
this.turnRight = function {
// some logic here
return this;
}
this.pickUpItem = function {
// some logic here
return this;
}
};
var frodo = new avatar();
frodo.turnLeft().turnRight().pickUpItem();
这正是我想要的。谢谢这正是我想要的。谢谢