【问题标题】:Uncaught TypeError: Cannot read property 'hasOwnProperty' of undefined未捕获的类型错误:无法读取未定义的属性“hasOwnProperty”
【发布时间】:2021-04-28 04:20:30
【问题描述】:

我正在使用 fabric.js 在画布上绘制一些文本。我有一个创建文本标签的功能。我想让标签在被选中时运行一个功能。其语法是 label.on('selected', functionToCall()); 当我将函数设为匿名内部函数时,这可以正常工作,但是当我将它作为一个单独的函数分解时,我得到一个 Uncaught TypeError:

无法读取未定义的属性“hasOwnProperty”。

我做错了什么?

以下是对我不起作用的代码。这是 jsfiddle 上的 broken code,以及使用 anonymous function 设置的版本。

"use strict";

var canvas = new fabric.Canvas('c', {selection: false}),
  position = 50;

function onLabelSelection(theLabel) {
  if (theLabel.hasOwnProperty('edge')) {
    selectedEdge = theLabel.edge;
  } else {
    selectedEdge = null;
  }
}

function createLabel() {
  var label;
    
  label = new fabric.Text('Hello World', {
    left: position,
    top: position
  });
  position += 50;
    
  label.edge = null;

  label.on('selected', onLabelSelection(this));

  return label;
}

canvas.on('mouse:up', function() {
  var newLabel = createLabel(); 
  canvas.add(newLabel);
});

【问题讨论】:

    标签: javascript dom-events anonymous-function


    【解决方案1】:

    这个语法是label.on('selected', functionToCall())

    没有。事件处理程序的语法是传递处理程序函数,而不是调用它:

    label.on('selected', functionToCall);
    

    您可能想尝试label.on('selected', onLabelSelection.bind(this)) 或 - 因为createLablel 中的this 显然是undefined - 只是label.on('selected', onLabelSelection)

    【讨论】:

    • 当然。总是小事。谢谢你。
    • 你很幸运你使用了严格模式 :-) 否则你传递的this 将是window,你不会得到错误,而只是奇怪的行为……
    • 严格模式是我最好的朋友!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 2019-02-26
    • 2021-12-25
    相关资源
    最近更新 更多