简体   繁体   English

这和javascript中的闭包(在paper.js中工作)

[英]This and closures in javascript (working in paper.js)

I'm still wrapping my head around closures. 我仍然把头围在瓶盖上。

I'm working on a project using Paper.js and paperscript . 我正在使用Paper.jspaperscript进行项目。 I am trying to create line segments with a distance metric that stays in the center of the segment as it is moved. 我正在尝试创建具有距离度量的线段,该距离度量在移动时保持在线段的中心。

Instead of simply writing code to move the center and the line separately (which would be pretty simple), I've been seeing whether it could be possible to move the line and have the center follow. 我一直在查看是否有可能移动直线并让中心跟随,而不是简单地编写代码分别移动中心和直线(这很简单)。

This is proving difficult. 事实证明这很困难。 There may be several problems with it, but right now this is my current bugaboo. 可能有几个问题,但是现在this是我当前的bugaboo。 They way I have it set up now, this refers to the global object when the function is called, which of course not what I want. 现在我以他们的方式设置它, this是指调用函数时的全局对象,这当然不是我想要的。 But I can't figure out how to create what I want, which is of course a baked-in reference from the 'weight' element to the 'line' element. 但是我无法弄清楚如何创建自己想要的东西,这当然是从“重量”元素到“线”元素的固有参考。

How do I do this correctly? 如何正确执行此操作?

edge = new Group({
    children: [
        new Path.Line({
            from: gn.position,
            to: event.point,
            strokeColor: 'maroon',
            name: 'line'
        }),
        new PointText(function (){
            return {
                position: function () {
                    return this.previousSibling.position;
                }(),
                content: function () {
                    return this.previousSibling.length.toString();
                }(),
                name: 'weight'
            }
        }())
    ]
});

In order to give a better structure, and bind a this reference, you can start defining a constructor function: 为了提供更好的结构并绑定this引用,您可以开始定义构造函数:

function PointTextContent(name) {
  this.position = function () {
    return this.previousSibling.position;
  }.bind(this);
  this.content = function () {
    return this.previousSibling.length.toString();
  }.bind(this);
  this.name = name;

  PointText.call(this, this);
}

PointTextContent.prototype = PointText;

Then change your code to instantiate your new object. 然后更改您的代码以实例化您的新对象。

edge = new Group({
    children: [
        new Path.Line({
            from: gn.position,
            to: event.point,
            strokeColor: 'maroon',
            name: 'line'
        }),
        new PointTextContent('weight')
    ]
});

NOTE: I changed position and content to become functions, I see they were immediately invoked in your original code. 注意:我将positioncontent更改为功能,我看到它们立即在您的原始代码中被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM