当前位置 : 主页 > 大数据 > 区块链 >

使用__proto__进行简单的javascript委派

来源:互联网 收集:自由互联 发布时间:2021-06-22
我已经习惯了 Java,所以当我尝试这样的事情: function subSection(pattern){ this.total = 0; this.pattern = pattern; this.distance=0;}function enhancer(pattern){ __proto__:subSection; this.pattern = pattern;}function silencer(
我已经习惯了 Java,所以当我尝试这样的事情:

function subSection(pattern){
    this.total = 0;
    this.pattern = pattern;
    this.distance=0;
}

function enhancer(pattern){
    __proto__:subSection;
    this.pattern = pattern;
}

function silencer(pattern){
    __proto__:subSection;
    this.pattern = pattern;
}

var a = new enhancer("aaa");
document.write(a.distance)

我得到“未定义”.我以为我继承了总数和距离数据成员

function subSection(pattern){
    this.total = 0;
    this.pattern = pattern;
    this.distance=100;
}

function enhancer(pattern){
    this.__proto__=new subSection(pattern);
}

function silencer(pattern){
    this.__proto__=new subSection(pattern);
}

var a = new enhancer("aaa");
document.write(a.distance)​;

但它只是一个Mozilla专有财产,正如RobG所说.

DEMO.

更新:

function subSection(pattern){
    this.total = 0;
    this.pattern = pattern;
    this.distance=100;
}

function enhancer(pattern){
    function F(){};
    F.prototype = new subSection(pattern); // inherited subSection
    return new F();    
}

function silencer(pattern){
    function F(){};
    F.prototype = new subSection(pattern); // inherited subSection
    return new F();
}

var a = new enhancer("aaa");
document.write(a.distance)​;

DEMO.

有用链接:herehere.

网友评论