Javascript:获取父对象的原型`this` [英] Javascript: get the parent's prototype `this`

查看:69
本文介绍了Javascript:获取父对象的原型`this`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我致力于改进一些贝塞尔缓动函数,但对 this 有问题.基本上,一个 Ease 对象.

I work on improving some bezier easing functions and have a problem with this. Basically, an Ease object.

Ease.bezier = function(mX1, mY1, mX2, mY2) {
    return _bezier.processBezier(mX1, mY1, mX2, mY2);
};

var _bezier = Ease.bezier.prototype;

_bezier.processBezier = function (mX1, mY1, mX2, mY2) {

    console.log(this) // this shows the proper object       
    this.mX1 = mX1;
    this.mX2 = mX2;
    this.mY1 = mY1;
    this.mY2 = mY2;

   return _bezier.render;      
};

_bezier.render = function(aX){ 
    console.log(this) // this shows another object
    if (this.mX1 === this.mY1 && this.mX2 === this.mY2) return aX;

    if (aX === 0) return 0;
    if (aX === 1) return 1; 
    return _bezier.computeBezier(_bezier.gx(aX), this.mY1, this.mY2);       
};

_bezier.render 函数是绑定到补间引擎的函数,例如 tween.js,因此继承了它的 this,所以 this.mX1 的值和其他与贝塞尔相关的值在 _bezier 中是未定义的.渲染函数.

The _bezier.render function is the one that's bound to a tweening engine, like tween.js, and thus inherits it's this, so the values for this.mX1 and other bezier related values are undefined in the _bezier.render function.

如果我将 this 替换为 _bezier,动画会起作用,但对于所有其他动画将始终使用最后一个实例的值.

If I replace this with _bezier, animation works but will always use the last instance's values for all the other animations.

那么,问题是,有没有办法以某种方式从 _bezier.processBezier 中的 _bezier.render 函数中获取 this ?

So, the question is, is there a way to get this from _bezier.processBezier inside the _bezier.render function somehow?

或者我可以通过绑定函数来简化代码以访问正确的this?

Or perhaps I can simplify the code by binding functions in a way to access the right this?

非常感谢.

推荐答案

尝试使用 .bind() 方法来获得正确的this":

Try to use .bind() method to get the right 'this':

// ...
_bezier.processBezier = function (mX1, mY1, mX2, mY2) {

    console.log(this) // this shows the proper object
    this.mX1 = mX1;
    this.mX2 = mX2;
    this.mY1 = mY1;
    this.mY2 = mY2;

    // use .bind(this)
    return _bezier.render.bind(this);
};
// ...

这篇关于Javascript:获取父对象的原型`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆