Unable to read undefined property of function inside loop

I have an error: I cannot read the property to “shorten” undefined errors when performing my test. I want my loop to run a shrinking function to check if the string is longer than 20 characters, and if that limits it.

  function ListView(list) {
    this.list = list;
    this.converted;
  }

  ListView.prototype.convert = function() {
    var output = [];
    this.list.notelist.forEach(function(element) {
      this.shorten(element);
      output += "<li><div>" + element.text + "</div></li>";
    });
    this.converted = "<ul>" + output + "</ul>";
  };

  ListView.prototype.shorten = function(string) {
    if (string.length > 20) {
      return string.substring(0, 20);
    }
    return string;
  };

a list from another constructor, but I mocked him:

var mockList = { notelist: [{ text: "hello" }, { text: "goodbye" }] };
+4
source share
5 answers

There is a server problem in your code:

enter image description here

  • , , , this . function (element) { .. , this .

  • shorten . , , element .

, , :

<script>
    function ListView(list) {
        this.list = list;
        this.converted;
    }

    ListView.prototype.convert = function () {
        var output = [];

        var that = this;
        this.list.notelist.forEach(function (element) {
            that.shorten(element);
            output += "<li><div>" + element.text + "</div></li>";
        });
        this.converted = "<ul>" + output + "</ul>";
    };

    ListView.prototype.shorten = function (el) {
        var string = el.text;

        if (string.length > 20) {
            el.text = string.substring(0, 20);
        }
    };

    var mockList = { notelist: [{ text: "hello" }, { text: "goodbye0123456789012345" }] };
    var listview1 = new ListView(mockList);
    listview1.convert();
    alert(listview1.converted);

</script>

goodbye0123456789012345 , goodbye0123456789012.

+2

this forEach :

  ListView.prototype.convert = function() {
    var output = [];
    this.list.notelist.forEach(function(element) {
      this.shorten(element);
      output += "<li><div>" + element.text + "</div></li>";
    }.bind(this));
    this.converted = "<ul>" + output + "</ul>";
  };

this.list.notelist.forEach((element) => {
  this.shorten(element);
  output += "<li><div>" + element.text + "</div></li>";
});

:

+1

Try to snap this

this.list.notelist.forEach(function(element) {
      this.shorten(element);
      output += "<li><div>" + element.text + "</div></li>";
    }.bind(this));
0
source

forEach takes a second argument, which is thisArg, by default it is undefined.

Try the following:

   this.list.notelist.forEach(function(element) {
      this.shorten(element);
      output += "<li><div>" + element.text + "</div></li>";
    }, this); // <-- note the `this` argument passed here
-2
source

Source: https://habr.com/ru/post/1691551/


All Articles