gpt4 book ai didi

javascript - 为什么创建实例变量后标题没有正确设置?

转载 作者:行者123 更新时间:2023-12-01 03:06:11 25 4
gpt4 key购买 nike

我正在尝试设置一个基本示例,我可以扩展我的主程序。我的问题是为什么标题不等于“HeyBARK”?我将 book 作为 bookTitles 类的一部分,所以设置的标题不应该自动添加树皮吗?

完成此操作后,我还需要引用我在原始作业中创建的大写方法。这个想法是,一旦像下面的代码片段那样设置了书名,我就会将该值传递到方法中并将其设置为等于返回结果。由于 setter 方法将接收整个对象,因此如何仅访问要修改的标题?

class bookTitle {
constructor(title){
this.title = title + "BARK";
}

// Everything in comments is part of the second paragraph in the
// question, I will psuedo code it

// getter the object here to access its title

// use a setter to call my capitalization method to capitalize certain
// words in the title

// title creator method that returns the modified value, will be called in setter

// cap method that purely caps the correct words, will be called within
// title creator
}

var book = new bookTitle();
console.log(book); //title is undefinedBARK as expected
book.title = "Hey";
console.log(book); // currently returns Hey, not HeyBARK

如果它对我有帮助的话,这里是我当前工作解决方案的实际代码,前几天一位优秀的开发人员能够使其在隔离环境中工作,但现在我正在尝试修改它以 setter 方式工作。

titleCreator(string) {
// Note that this isn't meant to be a fully fledged title creator, just designed to pass these specific tests
var littleWords = ["and", "over", "the"]; // These are the words that we don't want to capitalize

var self = this; // doesn't need to be here, just for syntax sugar, using this searches for things inside this class

var modifiedString = string
.split(' ') // Splits string into array of words, basically breaks up the sentence
.map(function(word,index) {
if (index == 0) {
return self.capitalize(word); // capitalize the first word of the string
} else if (littleWords.indexOf(word) == -1) {
return self.capitalize(word); // capitalize any words that are not little, the -1 is returned by indexOf if it can't find the word in the array
} else if (littleWords.indexOf(word) >= 0) {
return word; // do not capitalize as this word is in the list of littleWords
}
})
.join(' '); // Joins every element of an array into a string with a space inbetween each value. Basically you created a sentence from an array of words

return modifiedString;

}

capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
// This function just capitalizes the word given to it
}

最佳答案

我认为您在这里误解了构造函数的概念。构造函数构建给定类的新实例,在本例中,您创建 BookTitle 类的实例。创建新实例后,构造函数不再对其具有任何权力。使用大写字母命名类并使用小写字母命名实例也是一个很好的做法。

要实现您想要的效果,您需要为您的属性指定 getter 和 setter,例如:

class BookTitle {
constructor(title){
this.title = title;
}

get title() {
return this._title ;
}

set title(title) {
this._title = title + 'BARK';
}
}

let bookTitle = new BookTitle();
bookTitle.title = 'test';
console.log(bookTitle.title);

关于javascript - 为什么创建实例变量后标题没有正确设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46163410/

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