未捕获的TypeError:无法读取未定义的属性'hasOwnProperty'

 木头人2幸福 发布于 2023-01-15 15:45

我正在使用fabric.js在画布上绘制一些文本.我有一个创建文本标签的功能.我想让标签在选中时运行一个功能.这个的语法是label.on('selected', functionToCall());当我使函数成为一个匿名的内部函数时这很好用,但当我把它作为一个单独的函数分解时,我得到一个未捕获的TypeError : Cannot read property 'hasOwnProperty' of undefined. 我究竟做错了什么?

以下代码对我不起作用.这是jsfiddle 上的破解代码,以及使用匿名函数设置的版本.

"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);
});

Bergi.. 7

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

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

label.on('selected', functionToCall);

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有