gpt4 book ai didi

javascript - JavaScript 中的继承

转载 作者:行者123 更新时间:2023-12-02 17:26:24 27 4
gpt4 key购买 nike

我有下一个带有继承的代码。

function FileS(){}
FileS.prototype.getS = function (num){
console.log(num);
}
FileS.prototype.getDynamic = function(){
// WHAT I need to write here, so the function would call the DYNAMIC function
}

S3.prototype= new Files();
S3.prototype.constructor = S3();
function S3(){}
S3.prototype.getS = function (num){
console.log("This is for S3: " + num);
}

function dataE(u){
var s3 = new S3();
s3.getDynamic();
}

据我了解,s3将调用FileS.protortpe.getDynamic ,因为S3中没有这个功能原型(prototype)。但现在,我想要 FileS.protortpe.getDynamic将调用s3.protortpe.getS ,如果类型是 S3 ,和FileS.prototype.getS否则。我该怎么做(不指定 s3FileS ,因为这是更多类型..)?

最佳答案

以下是使用构造函数设置原型(prototype)层次结构的正确方法:

// ==== FileS ====
function FileS() {
}
// Add any FileS prototype things to `FileS.prototype`

// ==== S3 ====
function S3() {
FileS.call(this); // You could pass args here if appropriate
}
S3.prototype = Object.create(FileS.prototype);
S3.prototype.constructor = S3; // Optional, but a good idea
// Add any S3 prototype things to `S3.prototype`

...如果旧版浏览器需要的话,我们会填充单参数版本的Object.create,如下所示:

if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "The multiple-argument version of Object.create cannot be shimmed.";
}
function ctor() { }
ctor.prototype = proto;
return new ctor();
};
}
<小时/>

因为这是相当多的样板文件,我有一个 small helper script called Lineage为我做这件事。 这些天我使用 ES2015 的 class 语法和像 Babel 这样的转译器.

关于javascript - JavaScript 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23467857/

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