javascript - 未捕获的类型错误 : Cannot read property 'hasOwnProperty' of undefined

标签 javascript dom-events anonymous-function

我正在使用 fabric.js 在 Canvas 上绘制一些文本。我有一个创建文本标签的功能。我想让标签在被选中时运行一个函数。它的语法是 label.on('selected', functionToCall()); 当我将函数设为匿名内部函数时,这很好用,但是当我将它分解为一个单独的函数时,我得到一个未捕获的类型错误:

Cannot read property 'hasOwnProperty' of undefined.

我做错了什么?

下面是对我不起作用的代码。这是 broken code在 jsfiddle 上,一个版本设置了 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);
});

最佳答案

The syntax for this is label.on('selected', functionToCall())

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

label.on('selected', functionToCall);

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

关于javascript - 未捕获的类型错误 : Cannot read property 'hasOwnProperty' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23610476/

相关文章:

javascript - 用 javascript 扩展元素,最好的方法是什么?

javascript - 停止特定处理程序的事件传播

javascript - chrome.tabs.getSelected 在使用 list 版本 2 的最新 Chrome 上未定义?

java - 如何在 Java 中编写匿名函数?

javascript - 高级参数使用

javascript - JSON-Schema Draft-04 - OneOf 需要

javascript - MongoDB/Mongoose 查询生成器

javascript - 如何制作一个真正的 Javascript 计时器

php - 如何在 php 的闭包中使用 $this

javascript - 比较和打印 Bootstrap 面板内的元素