2014-03-26 52 views
0

這是我第一次在JS中創建一個對象。使用JavaScript的對象源錯誤

有人能幫我理解酸味爲什麼不起作用嗎?

這是完整的源代碼:

<script> 
function person(firstname,lastname,age,eyecolor) { 
    this.firstname=firstname; 
    this.lastname=lastname; 
    this.age=age; 
    this.eyecolor=eyecolor; 

    function getName() { 
     return this.firstname; 
    } 
} 

var myFather = new person("John","Doe",50,"blue"); 
document.write(myFather.getName()); 
</script> 

回答

0
function getName() { 
    return this.firstname; 
} 

應該

this.getName = function() { 
    return this.firstname; 
} 

而且最好是這樣的方法附着的person原型。

person.prototype.getName = function() { 
    return this.firstname; 
} 
+0

謝謝!它的工作=] – user3419680

+0

你可以解釋一下爲什麼? –

+0

@ZaheerAhmed這是一個漫長的故事,但這可能有所幫助:http://stackoverflow.com/a/16063711/1641941 – HMR

0

這裏是代碼。

<script> 
function person(firstname,lastname,age,eyecolor) { 
    this.getName = function getName() { 
     return firstname; 
    } 
} 

document.write((new person("John","Doe",50,"blue")).getName()); 
</script>