这是我的代码的一部分:
class Light {
constructor(xpos,zpos,ypos,range,diffuser,diffuseg,digguseb,intensity,angle,exponent) {
this.xpos = xpos;
this.ypos = ypos;
this.zpos = zpos;
this.range = range;
this.diffuser = diffuser;
this.diffuseg = diffuseg;
this.diffuseb = diffuseb;
this.intensity = intensity;
this.angle = angle;
this.exponent;
[...]
有没有办法将所有给定的参数变量移动到this
,以便我以后可以访问它们?
var lt = new Light(0,12,15,...);
alert(lt.zpos); //outputs '12'
我正在寻找将这11条this
行放到一个
答案 0 :(得分:0)
这可以满足您的需求。 mapArgsToThis
中获取参数名称的部分取自here。 mapArgsToThis
将是你想要懒惰时使用的辅助函数。
var mapArgsToThis = function(func, args, thisPointer) {
var argsStr = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
var argNames = argsStr.split(',').map(function(arg) {
return arg.replace(/\/\*.*\*\//, '').trim();
}).filter(function(arg) {
return arg;
});
var argValues = Array.prototype.slice.call(args);
argNames.forEach(function(argName, index) {
thisPointer[argName] = argValues[index];
});
};
var MyConstructor = function(xpos,zpos,ypos,range,diffuser,diffuseg,digguseb,intensity,angle,exponent) {
mapArgsToThis(MyConstructor, arguments, this);
};
var myInstance = new MyConstructor(1,2,3,4,5,6,7,8,9,0);
console.log(myInstance);

即使这是一个解决方案,我也不推荐它。输入映射到this
属性的参数对您的手指有好处,并且更容易让其他人阅读并了解正在进行的操作。在分配到this
之前,它也不允许对参数值进行任何处理。