gpt4 book ai didi

javascript - 使用 __proto__ 的简单 javascript 委托(delegate)

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:27:17 24 4
gpt4 key购买 nike

我习惯了 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)

我得到“未定义”。我以为我继承了total和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)​;

但正如 RobG 所说,它只是 Mozilla 的专有属性(property)。

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 .

关于javascript - 使用 __proto__ 的简单 javascript 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11075847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com