JavaScript无法在object.create(baseObject)

时间:2015-07-30 08:07:14

标签: javascript prototype

我是javascript的新手。我通过合并建议的答案编写了一些代码。现在,代码块在一次性场景中工作,而不在其他场景中工作。

<script langugage="JavaScript">

var baseObject = {
    name:"sunrise",
    age:39,
    printProperties:function(){
        console.log("Base class-> Name:Age:"+this.name+":"+this.age);
    }
}
baseObject.printProperties();
console.log(baseObject); 

/* This code block works fine */

var derivedObject2=Object.create(baseObject);
    derivedObject2.education="M.C.A"
    derivedObject2.printProperties=function(){  
        console.log("Derived -> Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
    }
 derivedObject2.printProperties();
 console.log(derivedObject2);


/*
derivedObject.__proto__ = baseObject;
derivedObject.printProperties(); // Works fine
*/

/* This code block does not work  */

var derivedObject=Object.create(baseObject,{
      education:{value:"MCA"},
      //education:"MCA",
      printProperties:function(){  
        console.log("Derived -> Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
        return this;
      }
});

derivedObject.printProperties(); // Getting error here, 
console.log(derivedObject);


</script>

这是我的错误:

Error:  Uncaught TypeError: derivedObject.printProperties is not a function

2 个答案:

答案 0 :(得分:1)

使用Object.create()

var baseObject = {
    name:"sunrise",
    age:39,
    printProperties:function(){
        console.log("Name:Age:"+this.name+":"+this.age);
    }
}

然后

var derivedObject=Object.create(baseObject);
    derivedObject.education="M.C.A"
    derivedObject.printProperties=function(){  
 console.log("Name:Age:Education:"+this.name+":"+this.age+":"+this.education);
        }
 derivedObject.printProperties();

现在,derivedObject将继承基础对象的所有属性

修改 你可以这样做

var derivedObject=Object.create(baseObject,{
              education:{value:"MCA"},
              printprop:function(){}
});

Object.create()抽象出与原型相关的大部分复杂性

答案 1 :(得分:0)

prototype是javascript中构造函数的属性。但是你正试图在对象中实现原型。这是不可能的。

请参阅实现原型概念的示例。

function baseObject (){
    this.name = "john";
    this.age = 25;
}
function derivedObject (){
    this.gender = "male";
    this.occupation = "Engineer";
}

derivedObject.prototype = new baseObject();
var d = new derivedObject();
console.log(d.name);
console.log(d.gender);