<body>
<p id="id"></p>
<script>
function StringBuilder() {
this._Buffer = [];
StringBuilder.prototype = {
Constructor: StringBuilder,
add: function (str) {
this._Buffer.push(str);
},
toString: function () {
return this._Buffer.join('');
}
}
}
var sb = new StringBuilder();
sb.add = "obber";
sb.add = "stadspolizie";
var id = document.getElementById("id");
id.innerText = sb.toString();
</script>
</body>
<!-- all I see on the screen is [onject Object] how can I display the text there? -->
答案 0 :(得分:0)
首先,当add
用作setter
(函数调用)时,您正在使用method
,如sb.add = "obber";
。换句话说:
:此:强>
sb.add("obber");
应该是:
add
之后,如果您尝试运行该undefined
方法,则会注意到function StringBuilder() {
this._Buffer = [];
}
StringBuilder.prototype = {
Constructor: StringBuilder,
add: function(str) {
this._Buffer.push(str);
},
toString: function() {
return this._Buffer.join('');
}
};
var sb = new StringBuilder();
sb.add("obber");
sb.add("stadspolizie");
var id = document.getElementById("id");
id.innerText = sb.toString();
方法为<p id="id"></p>
。那是因为你需要在构造函数之外移动原型方法。
最后的例子:
{{1}}
{{1}}