创建一个模拟类构造函数的方法
我想创建一个在创建对象实例时自动实现的方法,就像类构造函数的概念一样。创建一个模拟类构造函数的方法
function myString(string) {
// Storing the length of the string.
this.length = 0;
// A private constructor which automatically implemented
var __construct = function() {
this.getLength();
}();
// Calculates the length of a string
this.getLength = function() {
for (var count in string) {
this.length++;
}
};
}
// Implementation
var newStr = new myString("Hello");
document.write(newStr.length);
我当执行上面的代码中出现以下错误信息:TypeError: this.getLength is not a function
。
UPDATE:
问题是在this
范围。 以下是updade后的构造方法:
var __construct = function(that) {
that.getLength();
}(this);
BERGI在这个线程的答案是更为相关:How to define private constructors in javascript?
虽然你可以创建一个方法有点粗称为init
,然后调用在底部该方法你的函数,所以当你实例化一个新的对象时,代码将被运行。
function myString(string) {
//Initalization function
this.init = function() {
this.calcLength();
}
// Storing the length of the string.
this.length = 0;
this.getLength = function() {
return this.length;
}
// Calculates the length of a string
this.calcLength = function() {
for (var count in string) {
this.length++;
}
};
this.init();
}
// Implementation
var newStr = new myString("Hello");
var element = document.getElementById('example');
element.innerText = newStr.getLength();
编辑:我知道有更好的方法来实现这一目标,但这可以完成工作。
不要使用'init'方法。只需将相应的代码放入构造函数中。 – Bergi
谢谢。你的方式是另一种方式,但不是我想要的。 –
@Bergi我只是在另一个线程中阅读你的答案+1的实现非常好,我学到了一些新东西。编辑你的答案到我的。 –
'this'在'__construct'是不是你认为它是 - 当你解决这个问题,你还需要移动下面其中'this.getLength'定义代码 –
@JaromandaX:对不起,但我不明白你在'__construct中的这个是不是你认为它是什么意思'。 –
[JavaScript对象中的构造函数]的可能重复(http://*.com/questions/1114024/constructors-in-javascript-objects) – Ryan