编程语言
首页 > 编程语言> > javascript-链接对象时如何使用相同的方法?

javascript-链接对象时如何使用相同的方法?

作者:互联网

var string = function (base) { 
  return { 
    add: function (added) {
      return base + added;
  }
 }
}

text = string("robots").add(" are awesome");

console.log(text);

// robots are awesome

text2 = string("robots").add(" are awesome").add(" everytime!");

console.log(text2);

// TypeError: Object robots are awesome has no method 'add'

我该如何工作?您如何在函数范围内的某些对象之间共享“添加”方法?

解决方法:

可以是具有功能继承和级联的achieved. OP似乎要这样做.没有伪古典继承.

var string = function (someStartString) {
    var that = {
        append: function (newString) {
              that.currentString += newString;
              return that;//enable cascades        
        }
        ,currentString: someStartString
     };
     return that;
}

调用示例

var textObj = string("robots").append(" are awesome");

console.log(textObj.currentString);//output: robots are awesome

// robots are awesome

var text2Obj = string("robots").append(" are awesome").append(" everytime!");

console.log(text2Obj.currentString);//output: robots are awesome everytime!

标签:method-chaining,javascript
来源: https://codeday.me/bug/20191202/2085527.html