2013-09-27 41 views
0

我有這樣的方法:使用Javascript - 遺漏的類型錯誤:對象沒有方法

var stopwatch = function() { 
    this.start = function() { 
     (...) 
    }; 

    this.stop = function() { 
     (...) 
    }; 
}; 

當我嘗試調用它:

stopwatch.start();

我得到Uncaught TypeError: Object (here is my function) has no method 'start'。我究竟做錯了什麼?

回答

3

當函數stopwatch運行,從來沒有運行功能要分配功能this.startthis.stop

它看起來像你想要的構造函數,與一些原型。

// By convention, constructor functions have names beginning with a capital letter 
function Stopwatch() { 
    /* initialisation time logic */ 
} 

Stopwatch.prototype.stop = function() { }; 
Stopwatch.prototype.start = function() { }; 

// Create an instance 
var my_stopwatch = new Stopwatch(); 
my_stopwatch.start(); 
1

爲什麼不只是做new stopwatch().start()

+0

因爲你以後無法結束這種秒錶而不保存在一個變量。 – DCoder

+1

那麼,爲什麼不把實例賦值給一個變量,就像其他答案一樣呢? :P – Quv

1

你需要調用start功能這樣,

var obj = new stopwatch(); 
obj.start(); 

您可以創建該方法的一個實例,並進入啓動功能。

1

您需要首先創建一個新的對象,只有這樣,你可以調用它的功能:

var stopwatch = function() { 
    this.start = function() { 
     console.log('test'); 
    }; 

    this.stop = function() { 

    }; 
}; 

var s = new stopwatch(); 
s.start(); 

http://jsfiddle.net/9EWGK/

相關問題