gpt4 book ai didi

javascript - JS函数和抽象类和原型(prototype)

转载 作者:行者123 更新时间:2023-11-30 11:06:45 26 4
gpt4 key购买 nike

这是我的代码的简化版本:

  function TextBox () {
this.builddom = function () {
// Building the text dom
}
}
function ImageBox () {
this.builddom = function () {
// Building the image dom
}
}
function Box (type) {
var handler =
(type == 'text') TextBox :
(type == 'Image') ImageBox : null;
if (handler) (handler).call (this);

this.builddom = function () {
// Here I would like to call the correct builddom function for the type.
}
}
var textbox = new Box ('text');
textbox.builddom ();

如果 Box.builddom 不存在,这可以正常工作,调用与特定类型关联的 builddom 函数。但是我需要在 Box 中做一些通用的事情,然后调用特定的 builddom。如果我给 Box builddom 一个不同的名字,比如 Box.dobuilddom,也可以,但是会破坏对 Boxes 的通用访问。

我认为一些巧妙的原型(prototype)操作可以完成这项工作,但我找不到。

最佳答案

也许避免原型(prototype)设计并使用组合会更好:

function TextBox(box) {
this.builddom = function() {
console.log('Building the text dom', box.props);
}
}

function ImageBox(box) {
this.builddom = function() {
console.log('Building the image dom', box.props);
}
}

function Box(props) {
this.props = props;
this.builddom = function() {
throw new Error('unsupported function');
}
}

var textbox = new TextBox(new Box({size:5}));
textbox.builddom();

关于javascript - JS函数和抽象类和原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55299811/

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