2012-03-02 90 views
0
var Person = function(){}; 


function klass() { 
    initialize = function(name) { 
      // Protected variables 
      var _myProtectedMember = 'just a test'; 

      this.getProtectedMember = function() { 
      return _myProtectedMember; 
      } 

      this.name = name; 
       return this; 
     }; 
    say = function (message) {     
      return this.name + ': ' + message + this.getProtectedMember(); 
      // how to use "return this" in here,in order to mark the code no error. 
     }; 
//console.log(this); 

return { 
       constructor:klass, 
     initialize : initialize, 
     say: say 
    } 
    //return this; 
} 

Person.prototype = new klass(); 
//console.log(Person.prototype); 
new Person().initialize("I :").say("you ").say(" & he"); 

如何在“say”中使用“return this”,以便标记代码没有错误。Javascript“return this”符合“return”?

我想知道如何在已经返回alrealy的函数中“连锁调用”?

+2

你的功能可以返回响应消息或对象本身以允许链接。它不能同时返回。 – Simon 2012-03-02 10:57:08

回答

0

您需要返回一个类实例来链式调用。我建议你为所有可以存储类的输出的对象创建一个基类,并将它返回到“toString”或类似的函数中,也许是“输出”。然后

您的代码变成:可以返回

(new Person()).initialize("I :").say("you ").say(" & he").toString(); 
0

只有一个对象。

所以你有两个选择。

一个 - 显示消息的函数内部ANS返回this

say = function (message) {     
    // show the message here e.g. using an alert  
    alert(this.name + ': ' + message + this.getProtectedMember()); 
    // then return instance 
    return this; 
}; 

两个 - 返回包含实例和消息

say = function (message) { 
    message = this.name + ': ' + message + this.getProtectedMember();    
    return {message:message, instance:this}; 
}; 

一个对象,然后调用它像

new Person().initialize("I :").say("you ").instance.say(" & he");