有几种方法可以在javascript中获得类似行为的行为,最常见的似乎是基于这样的原型:
function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
Run Code Online (Sandbox Code Playgroud)
和基于闭包的方法类似于
function Vector(x, y, z) {
this.length = function() { return Math.sqrt(x * x + ...); }
}
Run Code Online (Sandbox Code Playgroud)
由于各种原因,后者更快,但我已经看到(我经常写)原型版本,并对其他人做了什么感到好奇.
原型还有对象文字方法:
var Vector = function(){};
Vector.prototype = {
init:function(x,y,z) {
this.x = x;
this.y = y;
this.z = z;
},
length:function() {
return Math.sqrt(x * x + ...);
}
};
var v1 = new Vector();
v1.init(1,2,3);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
580 次 |
| 最近记录: |