无法理解Javascript中的链接!

大家好,
我对道格拉斯·克罗克福德的"方法"方法有疑问.

选择 | 换行 | 行号
  1. Function.prototype.method = function (name, func) {
  2.     this.prototype[name] = func;
  3.     return this;
  4. };
  5. function azerizor(value) {
  6. this.value=value;
  7. }
  8.  
  9.  
  10. azerizor.method('toString', function () {
  11.  
  12.     return this.value;
  13. });
  14. var me = new azerizor('salam').toString();
  15.  
  16. alert(me);  

就是这个.但这里出现了关于退货的问题吗?
这里退货是什么意思?即使没有此方法,此方法也有效
把这个退掉
这条线.我读到过这方面的报道.所以有人说它是用来链接的.但我不明白如何使用这个"方法"函数来使用链接.提前感谢您的关注.我会等待你的回复!

# 回答1


可能在这种情况下链接不会有很大帮助,因为它可能会使您的代码变得不可读.其想法是,您可以在方法函数返回时调用其他方法.例如,假设您要将hashCode函数链接到Aerizor对象,您的代码如下所示:

选择 | 换行 | 行号
  1. Function.prototype.method = function (name, func) {
  2.     this.prototype[name] = func;
  3.     return this;
  4. };
  5. function azerizor(value) {
  6.     this.value=value;
  7. }
  8. azerizor.method('toString', function () {
  9.     return this.value;
  10. }) .method('hashCode', function() {
  11.       for(var ret = 0, i = 0, len = this.value.length; i < len; i++) {
  12.         ret = (31 * ret + this.value.charCodeAt(i)) << 0;
  13.       }
  14.       return ret;
  15. });
  16. var v = new azerizor('Cheers');
  17. alert("String: " + v.toString() + ", Hash Code: "+ v.hashCode());
  18.  
  19.  
# 回答2


如果您希望链接同名的函数,您可以将方法函数实现更新为如下所示:

选择 | 换行 | 行号
  1. Function.prototype.method = function (name, func) {
  2.     var fun = this.prototype[name];
  3.     if (typeof(fun) == "function") {
  4.         this.prototype[name] = function() {
  5.             fun.apply(this, arguments); 
  6.             return func.apply(this, arguments);
  7.         };
  8.     } else {
  9.         this.prototype[name] = func;
  10.     }
  11.     return this;
  12. };
  13.  

如果函数有返回,我不知道您将如何处理返回.在上面的例子中,我返回链上最后一个函数的结果.

# 回答3


非常感谢您的关注并为此花费时间!
# 回答4


非常感谢!

标签: Javascript

添加新评论