本文實例分析了JavaScript透過function定義物件並為物件新增toString()方法。分享給大家供大家參考。具體分析如下:
下面的JS程式碼透過function定義了一個movie對象,在movie對象內定義了一個toString方法,toString方法透過外部函數實作。
<script type="text/javascript"> function movieToString() { return("title: "+this.title+" director: "+this.director); } function movie(title, director) { this.title = title; this.director = director; this.toString = movieToString; //assign function to this method pointer } var aliens = new movie("Aliens","Cameron"); document.write(aliens.toString()); </script>
希望本文所述對大家的javascript程式設計有所幫助。