Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

context this 指向的问题 #16

Closed
popomore opened this issue Mar 9, 2013 · 9 comments
Closed

context this 指向的问题 #16

popomore opened this issue Mar 9, 2013 · 9 comments

Comments

@popomore
Copy link
Contributor

popomore commented Mar 9, 2013

var velocity = require('velocityjs');
var data = 'a = $a.get()';

function b(c) {
  this.c = c;
}
b.prototype.get = function() {
  return this.c;
};

var property = velocity.render(data, {
  a: new b(1)
});
console.log(property); // 输出 a = $a.get()

get 方法调用实例上属性的时候输出错误,如果改成字符串是正确的。

@popomore
Copy link
Contributor Author

popomore commented Mar 9, 2013

版本为 velocityjs@0.3.8

@popomore
Copy link
Contributor Author

popomore commented Mar 9, 2013

看了下,从 0.3.4 开始有这个问题

@shepherdwind
Copy link
Owner

出现这个问题是因为我在内部开放出this.eval用于解析vm字符串,在调用context和macros的方法的时候,把this指向了velocityjs对象 src/compile/references.js#L200 。

如果不改变context里面函数对应的this上线文,那么在函数里面就没法调用this.eval方法了。

@shepherdwind
Copy link
Owner

我想到一个稍微麻烦一些的方案是,只对特定的函数改变其中的this,比如你需要调用this.eval来执行velocityjs解析,那么你的context里面需要有一个方法,比如名字也是eval。

比如这样:

var velocity = require('../code/velocity.js/');
var data = 'a = $a.get()';

function b(c) {
  this.c = c;
}

b.prototype.get = function() {
  // this 指向的是b
  return this.c;
};

b.prototype.eval = function(str){
  // this 指向的是Velocity.Compile
  return this.eval(str);
};

var property = velocity.render(data, {
  a: new b(1)
});
console.log(property);

@popomore
Copy link
Contributor Author

popomore commented Mar 9, 2013

能否不改变 this,而是增加到属性上?比如所有的 this 上都增加个 eval,只要不重名。

@popomore
Copy link
Contributor Author

popomore commented Mar 9, 2013

var that = this;
ret.eval = function(str) {
  that.eval(str)
}
ret = ret.apply(ret, args);

如果只使用一个 eval 方法的话,是否可以这样

@shepherdwind
Copy link
Owner

嗯,这个方案比较好,我在context传入之初就给context增加一个eval方法。

shepherdwind added a commit that referenced this issue Mar 9, 2013
shepherdwind added a commit that referenced this issue Mar 9, 2013
@shepherdwind
Copy link
Owner

好了,我发布了一下0.3.9版本,并且增加了测试用例

@popomore
Copy link
Contributor Author

popomore commented Mar 9, 2013

修改神速 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants