Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对象源中的JavaScript错误_Javascript - Fatal编程技术网

对象源中的JavaScript错误

对象源中的JavaScript错误,javascript,Javascript,这是我第一次在JS中创建对象 有人能帮我理解为什么sourve不起作用吗 这是完整的来源: <script> function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; function getName() {

这是我第一次在JS中创建对象

有人能帮我理解为什么sourve不起作用吗

这是完整的来源:

<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>

职能人员(名字、姓氏、年龄、眼睛颜色){
this.firstname=firstname;
this.lastname=lastname;
这个。年龄=年龄;
this.eyecolor=eyecolor;
函数getName(){
返回这个.firstname;
}
}
var myFather=新人(“约翰”、“多伊”、50、“蓝色”);
document.write(myFather.getName());
应该是

this.getName = function () {
    return this.firstname;
}
最好将这种方法附加到
person
的原型上

person.prototype.getName = function () {
    return this.firstname;
}
这是代码

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

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

职能人员(名字、姓氏、年龄、眼睛颜色){
this.getName=函数getName(){
返回名字;
}
}
document.write((新人(“约翰”、“多伊”、50、“蓝色”)).getName();

你能解释一下原因吗?@ZaheerAhmed说来话长,但这可能会有所帮助:
<script>
function person(firstname,lastname,age,eyecolor) {
    this.getName =  function getName() {
        return firstname;
    }
}

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