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”,以标记代码没有错误。
我想知道如何在有返回的函数中‘链式调用’?
发布于 2012-03-02 19:15:10
你需要返回一个类实例来链式调用。我建议您为所有能够存储类输出的对象创建一个基类,并将其返回到"toString“或类似的函数中,可能是"output”。
然后你的代码就变成了:
(new Person()).initialize("I :").say("you ").say(" & he").toString();发布于 2012-03-02 20:51:52
只能返回一个对象。
所以你有两个选择。
One -显示函数内部的消息并返回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");https://stackoverflow.com/questions/9532077
复制相似问题