如何将构造函数的值传递给其他方法以进行修改?

3
该项目的目标是重构先前的解决方案以使用实际对象。当前,当我运行Jasmine测试时,会出现以下两个错误:
TypeError:无法读取未定义的'split'属性
TypeError:无法设置未定义的'title'属性
为什么类在我尝试将其传递到其他方法中时未能识别标题值?在我尝试将字符串值发送到titleCreator方法之前,它似乎可以工作,但现在它一直返回未定义。
class bookTitle {
    constructor(title) {
        this.title = this.titleCreator(title); // this sets a title value to the bookTitle object/class
    }

    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 modifiedString = this.string
        .split(' ') // Splits string into array of words, basically breaks up the sentence
        .map(function(word,index) {
            if (index == 0) {
                return capitalize(word); // capitalize the first word of the string
            } else if (littleWords.indexOf(word) == -1) {
                return 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
    }
}

module.exports = {
    bookTitle
}

编辑:这里是我的Jasmine测试案例。该程序的想法仅是通过这些案例。

var bookTitles = require ('./bookTitles.js');

describe('bookTitle', function() {

    var book; // this is the object that will be passed into the test cases, returns undefined here without beforeEach

    beforeEach(function() {
        book = new bookTitles.bookTitle(); // creates a new book instance before each test is run
    });

    describe('title', function() {
        it('should capitalize the first letter', function() {
            book.title = 'inferno';
            expect(book.title).toEqual('Inferno'); // works without capitalizing
        });

        it('should capitalize every word', function() {
            book.title = 'stuart little';
            expect(book.title).toEqual('Stuart Little');
        });

        describe('should capitalize every word except...', function() {
            describe('articles', function() {
                it('does not capitalize "the"', function() {
                    book.title = 'alexander the great';
                    expect(book.title).toEqual('Alexander the Great');
                });

                it('does not capitalize "a"', function() {
                    book.title = 'to kill a mockingbird';
                    expect(book.title).toEqual('To Kill a Mockingbird');
                });

                it('does not capitalize "an"', function() {
                    book.title = 'to eat an apple a day';
                    expect(book.title).toEqual('To Eat an Apple a Day');
                });
            });

            it('conjunctions', function() {
                book.title = 'war and peace';
                expect(book.title).toEqual('War and Peace');
            });

            it('prepositions', function() {
                book.title = 'love in the time of cholera';
                expect(book.title).toEqual('Love in the Time of Cholera');
            });
        });

        describe('should always capitalize...', function() {
            it('I', function() {
                book.title = 'what i wish i knew when i was 20';
                expect(book.title).toEqual('What I Wish I Knew When I Was 20');
            });

            it('the first word', function() {
                book.title = 'the man in the iron mask';
                expect(book.title).toEqual('The Man in the Iron Mask');
            });
        });
    });
});
1个回答

0

您正在尝试访问此代码行中的this.string

var modifiedString = this.string

在你设置this.string的值之前,也许你只是想使用传递给titleCreator的参数stringthis.stringstring不同。由于this.string从未被赋值,因此它是undefined,因此任何尝试访问其上的方法都将失败。

有点难以确定你的意图,但也许你想使用string而不是this.string

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 modifiedString = string
      .split(' ') // Splits string into array of words, basically breaks up the sentence
      .map(function(word,index) {
        if (index == 0) {
            return capitalize(word); // capitalize the first word of the string
        } else if (littleWords.indexOf(word) == -1) {
            return 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;
}

从您的错误描述来看,似乎您在调用bookTitle时可能存在问题(它应该作为构造函数调用,如下所示:)
let bk = new (yourModule.bookTitle)("some string") 

如果您需要帮助,请展示调用该构造函数的代码,这样我们也可以为您提供建议。

这是一段我不得不修复其他几个问题的工作代码:

    class bookTitle {
        constructor(title) {
            this.title = this.titleCreator(title); // this sets a title value to the bookTitle object/class
        }
    
        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;
    
            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
        }
    }
    
    let bookTitles = {
        bookTitle: bookTitle
    };
    
    let book = new bookTitles.bookTitle("some title of the book");
    console.log(book)

我必须修复的问题:

  1. this.string.split(...) 改为 string.split(...)
  2. 定义 selfthis
  3. 在两个地方使用 self.capitalize() 来正确调用方法,而不是使用 capitalize()
  4. 在调用构造函数时传入一个字符串(你的代码调用构造函数时未传入任何参数,这会导致构造函数出错)。你的代码要求在构造函数中传入一个字符串。

此外,你的代码似乎认为只需分配给 .title 属性就能运行 titleCreator() 方法并进行正确的大写处理。但实际上不行。分配给 .title 属性只是设置该属性,它不会运行任何方法。你可以定义一个 setter 方法来使其在分配给属性时运行代码,但更明智的做法可能是创建一个 setTitle() 方法来执行你想要的操作(调用 .titleCreator() 并将结果分配给 .title)。


我之前尝试过那种方式,但是我得到了相同的错误代码。我将编辑我的原始帖子以包含测试用例,对于缺乏上下文我感到抱歉。想法只是通过我编写的所有Jasmine测试用例。 - mcrav95
@mcrav95 - 还有几个问题。请查看我添加到答案中的可运行代码片段,以便您可以查看它创建的输出并列出我必须进行的更改。 - jfriend00
哇,非常感谢你的帮助,你真的超出了我的期望。我将检查答案以查看是否还有其他错误,再次感谢! - mcrav95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接