gpt4 book ai didi

javascript - JS对象结果之间的区别

转载 作者:行者123 更新时间:2023-11-29 17:48:44 26 4
gpt4 key购买 nike

我想知道为什么第一个对象实例化返回正确的“numPages”而第二个对象实例化返回与“undefined”相同的结果。希望有人能帮我澄清这个疑问。提前致谢!

// The constructor function
function Book(title, author, numPages) {
this.title = title;
this.author = author;
this.numPages = numPages;
}

// A method on the object
Book.prototype.read = function() {
this.currentPage = this.numPages;
console.log('You read ' + this.numPages + ' pages');
}


// Instatiation and object
// Returns numPages = 325
var book = new Book("Harry Potter", "J.K. Rowling", 574);

// Returns numPages as "undefined"
var book = new Book({
title: "Robot Dreams",
author: "Isaac Asimov",
numPages: 325
});

book.read();

最佳答案

在第一种情况下,您传递 3 个单独的参数,这些参数分配给对象的字段。

在第二种情况下,您将一个参数作为具有属性 title, author, numPages 的对象传递给第一个参数。所以只有第一个被分配,它是一个对象。

如果您在赋值后打印这些值,您可以看到在第一种情况下所有值都已传递,但在第二种情况下只有 {} 作为第一个参数传递到构造函数中。并将其分配给 title 属性。现在标题是对传递的对象的引用。

function Book(title, author, numPages) {
this.title = title;
this.author = author;
this.numPages = numPages;
console.log(' title - ' + this.title);
console.log(' author - ' + this.author);
console.log(' numPages - ' + this.numPages);
}

Book.prototype.read = function() {
this.currentPage = this.numPages;
console.log('You read ' + this.numPages + ' pages');
}

console.log('First book');
var book = new Book("Harry Potter", "J.K. Rowling", 574);

console.log('Second book');
var book = new Book({
title: "Robot Dreams",
author: "Isaac Asimov",
numPages: 325
});

这行代码

var book = new Book({
title: "Robot Dreams",
author: "Isaac Asimov",
numPages: 325
});

相当于

var book = new Book({
title: "Robot Dreams",
author: "Isaac Asimov",
numPages: 325
}, undefined, undefined);

如果你想要 2 个案例工作,你可以在 Book 本身上有工厂方法

function Book(title, author, numPages) {
this.title = title;
this.author = author;
this.numPages = numPages;
console.log(' title - ' + this.title);
console.log(' author - ' + this.author);
console.log(' numPages - ' + this.numPages);
}

Book.create = function (title, author, numPages) {
return new Book(title, author, numPages);
}

Book.createFromObject = function ({title, author, numPages}) {
return new Book(title, author, numPages);
}

Book.prototype.read = function() {
this.currentPage = this.numPages;
console.log('You read ' + this.numPages + ' pages');
}

console.log('First book');
var book = Book.create("Harry Potter", "J.K. Rowling", 574);

console.log('Second book');
var book = Book.createFromObject({
title: "Robot Dreams",
author: "Isaac Asimov",
numPages: 325
});

关于javascript - JS对象结果之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250256/

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