oop-如何获得这个javascript
我正在修改一些代码,使其功能更像c#中的一个类,这样就不必为每次出现都编写新的脚本。我在构造函数上遇到了我的作用域问题,我有这个构造函数oop-如何获得这个javascript,javascript,oop,Javascript,Oop,我正在修改一些代码,使其功能更像c#中的一个类,这样就不必为每次出现都编写新的脚本。我在构造函数上遇到了我的作用域问题,我有这个构造函数 function Game(canvas) { this.Polygon = function(size, pointCount){ this.size = size; this.pointCount = pointCount; this.corners = []; this.palett
function Game(canvas) {
this.Polygon = function(size, pointCount){
this.size = size;
this.pointCount = pointCount;
this.corners = [];
this.palette = [];
this.render = function (GameObject) {
this.makePolygon(GameObject, this.size, this.corners);
};
};
this.makePolygon = function(GameObject, size, corners){//other code...}
}
我的问题是在这个.render中,makePolygon在类中,所以这意味着一些不同的东西。我试过使用.bind(这个);但我不能让它工作
我肯定以前有人问过这个问题,但我发现没有一个答案对我有用。我在不同团队中使用的惯例是在javascript函数的顶部别名
this
,以避免这个确切的问题
例如:
this.Polygon = function(size, pointCount){
var my = this;
my.size = size;
my.pointCount = pointCount;
my.corners = [];
my.palette = [];
my.render = function (GameObject) {
my.makePolygon(GameObject, my.size, my.corners);
};
};
this.makePolygon = function(GameObject, size, corners){//other code...}
另一种选择,取决于此函数所在的位置,是按如下方式执行
// Somewhere at the top of this code snippet
var my = this;
//...
my.Polygon = function(size, pointCount){
my.size = size;
my.pointCount = pointCount;
my.corners = [];
my.palette = [];
my.render = function (GameObject) {
my.makePolygon(GameObject, my.size, my.corners);
};
};
my.makePolygon = function(GameObject, size, corners){//other code...}
将此设置为函数顶部(或“类”顶部)的其他内容
var self=this
,然后引用self
self.size=size[…]self.makePolygon…
我不明白为什么this
会有所不同,但您没有显示如何调用this.Polygon
和this.render
或外部this
与其他任何内容相关。多边形构造函数和makePolygon函数包装在函数游戏()中{ },这使得我可以拥有多个相同脚本的实例,但只维护一个.js文件。我使用了您的基本建议。感谢您的帮助!这不是最好的方式。有趣的文章,但它并没有说这是一个坏的选择。事实上,似乎有很多人支持它。存储本地脚本的简单性闭包中的变量,可以访问预期的,这对许多程序员很有吸引力。