为什么当我收到此消息“ this.getNewsFeedLook不是函数”时,为什么

时间:2019-05-22 09:08:55

标签: javascript function object

我知道有很多关于该主题的文章,但是我想知道我的代码,为什么this.getNewsFeedLook()不是函数?

define(["jquery"], function ($) {

    let objectNews = {

        title: undefined,
        type: undefined,
        img: undefined,
        link: undefined,
        content: undefined,
        newsFeedLook: this.getNewsFeedLook(),

        getNewsFeedLook: function () {
            let html = "" +
                "<div class='col-xl-3 col-lg-4 col-md-6 col-sm-6 col-12'>" +
                "   <div class='newsbox'>" +
                "       <a href='" + this.link + "'>" +
                "           <img src='" + this.img + "'>" +
                "           <div class='dark_folie'>" +
                "               <p>" + this.title + "</p>" +
                "               <span>" + this.type + "</span>" +
                "</div></a></div></div>";

            return html;
        },

    };
    return objectNews;
});

2 个答案:

答案 0 :(得分:0)

尝试在getNewsFeedLook之后定义属性newsFeedLook。它应该可以解决您的问题。

答案 1 :(得分:0)

获得this.getNewsFeedLook() is it not a function的原因是因为this不是指objectNews范围(您所期望的)。

简单的解决方法是创建newsFeedLook一个函数。然后,您的对象将如下所示:

let objectNews = {

    title: undefined,
    type: undefined,
    img: undefined,
    link: undefined,
    content: undefined,
    newsFeedLook: function(){ return this.getNewsFeedLook()},

    getNewsFeedLook: function () {
        let html = "" +
            "<div class='col-xl-3 col-lg-4 col-md-6 col-sm-6 col-12'>" +
            "   <div class='newsbox'>" +
            "       <a href='" + this.link + "'>" +
            "           <img src='" + this.img + "'>" +
            "           <div class='dark_folie'>" +
            "               <p>" + this.title + "</p>" +
            "               <span>" + this.type + "</span>" +
            "</div></a></div></div>";

        return html;
    },

};