如何在JavaScript中从子类透明地访问父类成员
我有以下代码:如何在JavaScript中从子类透明地访问父类成员,javascript,Javascript,我有以下代码: var Person = function () { this.Id = 0; this.Name = ""; }; var Emp = function () { this.OfficeEmail = ""; }; Emp.prototype = new Person(); Emp.prototype.constructor = Emp; var oEmp = ne
var Person = function () {
this.Id = 0;
this.Name = "";
};
var Emp = function () {
this.OfficeEmail = "";
};
Emp.prototype = new Person();
Emp.prototype.constructor = Emp;
var oEmp = new Emp();
alert(oEmp.hasOwnProperty('OfficeEmail'));//true
alert(oEmp.hasOwnProperty('Id'));//false
alert(oEmp.hasOwnProperty('Name'));//false
alert("Id" in oEmp); //true - inherited property
alert("Name" in oEmp); //true - inherited property
alert("OfficeEmail" in oEmp); //true - direct property
//----------------The following screws up-------------------------
oEmp.Id = 9999; //creates a new property in Emp instead of accessing from Person
oEmp.Name = "Scott"; //creates a new property in Emp instead of accessing from Person
oEmp.OfficeEmail = "Scott@yahoo.com";
//Now the output is different here
alert(oEmp.hasOwnProperty('OfficeEmail'));//true
alert(oEmp.hasOwnProperty('Id'));//true - supposed to be false
alert(oEmp.hasOwnProperty('Name'));//true - supposed to be false
虽然我知道我可以创建另一个属性(比如parent)并将其添加到Emp原型中,并使用parent访问父成员,但我只是想知道我是否可以仅使用childObject.parentProperty表示法实现对基类属性的透明访问,而无需在child中创建任何新的父属性,访问父成员。我不清楚您到底想要什么,但您可以访问您创建的任何属性,我不知道它们在hasOwnProperty中返回false,但在您的示例中,如果访问oEmp.Id,它将返回0您的个人Id。在上述情况下,如果我访问oEmp.Id作为上述脚本中的最后一条语句,它不会返回0。它返回9999。