JavaScript 无法在 object.create(baseObject) 之后访问相同的对象方法 [英] JavaScript unable to access same object method after object.create(baseObject)

查看:46
本文介绍了JavaScript 无法在 object.create(baseObject) 之后访问相同的对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JavaScript 新手.我通过合并建议的答案编写了一些代码.现在代码块在一个场景中工作,在其他场景中不起作用.

I am new to javascript. I have written some code by incorporating suggested answers. Now the code block is working in once scenario and not working in other scenario.

<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

推荐答案

使用 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();

现在派生对象将继承基础对象的所有属性

now the derivedObject will inherit all the properties of the base object

编辑你可以这样做

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

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

Object.create() abstracts most of the complexity that is associated with the prototypes

这篇关于JavaScript 无法在 object.create(baseObject) 之后访问相同的对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆