gpt4 book ai didi

Javascript:默认原型(prototype)字段显示使用 null 构造函数创建的对象未定义

转载 作者:行者123 更新时间:2023-11-28 18:21:26 25 4
gpt4 key购买 nike

我注意到下面代码中的一些行为我无法解释。我希望有人能启发我为什么会发生这种情况。

如果更容易阅读,下面的代码示例也可以在 JSFiddle 上找到。 https://jsfiddle.net/0b5rh4cg/

代码:

function Book() {

};

function Book (title, author) {
this.title = title;
this.author = author;
};

Book.prototype = {
title: "",
ISBN: "isbn",
length: 100,
genre: "genre",
covering: "covering",
author: "author",
currentPage: 0,

toString: function toString() {
console.log("toString Function");
console.log('Title: ' + this.title + '\n' +
'ISBN: ' + this.ISBN + '\n' +
'length: ' + this.length + '\n' +
'genre: ' + this.genre + '\n' +
'covering: ' + this.covering + '\n' +
'author: ' + this.author + '\n' +
'currentPage: ' + this.currentPage + '\n');
}
};

var book1 = new Book();
book1.toString();

var book2 = new Book("First edition", "Random");
book2.toString();

book1.toString() 的输出toString 函数标题:未定义国际标准书号:isbn长度:100流派:流派覆盖:覆盖作者:未定义当前页数:0

book2.toString() 的输出toString 函数标题:第一版国际标准书号:isbn长度:100流派:流派覆盖:覆盖作者:随机当前页数:0

我对作者和标题字段感到困惑。在 null 构造函数中,这些字段默认为“未定义”,而不是 Book 类原型(prototype)中设置的字段。

感谢任何对此提供帮助的人。

干杯,卡姆。

最佳答案

JavaScriptJava(或其他编程语言)不同,在 Java(或其他编程语言)中,您可以使用具有相同名称的方法或多个构造函数(如果它们具有不同数量或类型的参数)。在本例中,您已将 Book() 替换为 Book(title,author)

为了实现你想要的,你可以这样做:

function Book (title, author) {
this.title = title||"";
this.author = author||"";
};

在这种情况下,titleauthor 将默认为空的String

或者类似这样的东西:

function Book (title, author) {
this.title = title && author ? title : "";
this.author = title && author ? author : "";
};

关于Javascript:默认原型(prototype)字段显示使用 null 构造函数创建的对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39795230/

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