我正在尝试设置一个基本示例,我可以扩展我的主程序。我的问题是为什么标题不相等" HeyBARK"?我把书作为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
}
答案 0 :(得分:1)
book.title = "Hey";
这是在标题中写出值树皮。 构造函数在创建时被调用。因此,您执行上述行会替换该值,并且不会重新调用构造函数。
答案 1 :(得分:1)
我认为,你在这里误解了构造函数的概念。构造函数构建给定类的新实例,在这种情况下,您将创建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);
答案 2 :(得分:0)
您应该在实例化时指定标题,因此您应该使用:
var book = new bookTitle('Hey');
book === 'Hey Bark'
否则,您在实例化后重置整个title属性,因此它忽略了标题在初始化时的设置方式。