2016-12-09 42 views
1

我想創建一個在創建對象實例時自動實現的方法,就像類構造函數的概念一樣。創建一個模擬類構造函數的方法

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); 
+0

'this'在'__construct'是不是你認爲它是 - 當你解決這個問題,你還需要移動下面其中'this.getLength'定義代碼 –

+0

@JaromandaX:對不起,但我不明白你在'__construct中的這個是不是你認爲它是什麼意思'。 –

+0

[JavaScript對象中的構造函數]的可能重複(http://stackoverflow.com/questions/1114024/constructors-in-javascript-objects) – Ryan

回答

1

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(); 

編輯:我知道有更好的方法來實現這一目標,但這可以完成工作。

編輯2:小提琴https://jsfiddle.net/ntygbfb6/3/

+0

不要使用'init'方法。只需將相應的代碼放入構造函數中。 – Bergi

+0

謝謝。你的方式是另一種方式,但不是我想要的。 –

+0

@Bergi我只是在另一個線程中閱讀你的答案+1的實現非常好,我學到了一些新東西。編輯你的答案到我的。 –

相關問題