如何从JavaScript中的子类透明地访问父类成员

时间:2012-08-15 16:12:47

标签: javascript

我有以下代码:

    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”表示法的属性(不在子项中创建任何新的“父”属性,以访问父成员)。

0 个答案:

没有答案
相关问题