[英]Error when calling methods within a Javascript class
我已经定义了一个用于矩阵转换(在html5画布上绘制点的)的javascript类,它具有多种方法(例如,乘法,旋转,缩放,平移)。 在我的rotate方法中,我需要调用乘法,但是由于它是类内定义的另一种方法,因此必须以不同于在类定义之外被调用的方式进行调用。 对于类构造函数,我有:
function Transform() {
this.identity();
}
对于旋转方法:
Transform.prototype.rotateX = function(rad) {
var c = Math.cos(rad);
var s = Math.sin(rad);
var rx = [[1, 0, 0, 0],
[0, c, -s, 0],
[0, s, c, 0],
[0, 0, 0, 1]];
this.m = multiply(rx, this.m);
document.write('matrix rx:<br />');
display(rx);
document.write('rx * this.m =<br />');
display(this.m);
};
我来自具有OOP的C ++背景,因此这种定义类的方式似乎有些奇怪,但是似乎您应该能够调用类中定义的函数,而无需使用点运算符(类似于C ++中的方式),如果您如果使用范围限定符定义了方法,则可以自由访问任何类的数据。 出于某种原因,在javascript中,肯定不是这种情况,因为我遇到了错误: Uncaught ReferenceError: multiply is not defined
在类定义的内部和外部调用Javascript类中定义的方法的正确方法是什么?
但是似乎您应该能够调用类中定义的函数,而无需像C ++中那样使用点运算符
不。 在JavaScript中, this
不是可选的,因此,如果multiply
附加到对象(从原型,或者只是在构造函数中分配给对象),则需this
:
this.m = this.multiply(rx, this.m);
你可能会想调用一个在范围内的功能,它不要求this
。 这是这三个示例:
function Thingy(prop) { this.prop = prop; // Here's a "method" we add in the constructor: this.method1 = function() { snippet.log("Thingy#method1, prop = " + this.prop); }; }; Thingy.prototype.method2 = function() { snippet.log("Thingy#method2, prop = " + this.prop); }; Thingy.prototype.method3 = function() { snippet.log("Thingy#method3, prop = " + this.prop); this.method1(); this.method2(); inScopeOnlyForMethod3(); inScopeOnlyForMethod3.call(this); function inScopeOnlyForMethod3() { snippet.log("inScopeOnlyForMethod3, prop = " + this.prop); } }; var t = new Thingy(42); t.method3();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
请注意, this
在JavaScript中是根本不同的 this
C ++中。 在JavaScript中, this
对function
的功能通常是由函数是怎么被调用决定,而不是在那里的定义。 (ES2015(最新的JavaScript标准)定义了不使用function
关键字的“箭头”函数,它们从创建它们的上下文中继承了this
关键字。)
同样,C ++类从根本上不同于 JavaScript的构造函数和原型。 (请注意,您可以使用构造函数或直接通过Object.create
进行JavaScript的原型继承。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.