js 中的对象问题,这个写法该怎么改?

2015-03-13 22:23:11 +08:00
 EXDestroyer

function(x,y){
this.repeatMap = function (repeatX, repeatY) {
this.repeatX = repeatX;
this.repeatY = repeatY;
return this;

}

this.aMartix= function (){
var flagMatrix = new Array();
for ( i = 0; i < tileNumX; i++) {
flagMatrix[i] = new Array();
}

for ( x = 0; x < tileNumX; x++) {
    for ( y = 0; y < tileNumY; y++) {

        flagMatrix[x][y] = new repeatMap(repeatX, repeatY);
        //这里报错了
        }
    }

}

}

3398 次点击
所在节点    JavaScript
15 条回复
7anshuai
2015-03-14 01:04:13 +08:00
repeatMap是对象的方法,将 new repeatMap() 改为 this.repeatMap() 试试
kmvan
2015-03-14 01:07:20 +08:00
var that =this;
new that.repeatMap()
blacktulip
2015-03-14 01:11:28 +08:00
报的什么错?
guoziyan
2015-03-14 10:36:49 +08:00
this 的作用域发生改变 可以使用
function Set(){
this.x=1;
};
Set.prototype.get=function(){
console.log(this.x)
}
EXDestroyer
2015-03-14 10:57:36 +08:00
@blacktulip undefine is not a function
lalalanet
2015-03-14 11:52:32 +08:00
flagMatrix[x][y] = new repeatMap(repeatX, repeatY);

执行的时候 ,寻找的是局部方法,this. repeatMap绑定到this上了。

var that = this;

function repeatMap (repeatX, repeatY) {
that.repeatX = repeatX;
that.repeatY = repeatY;
return that;

}

this. repeatMap = repeatMap;


不过楼主你这玩意写的真烂,完全不懂js的基本做法。
EXDestroyer
2015-03-14 11:57:19 +08:00
@lalalanet 确实是写的烂,,现在对js还停留在简单的DOM操作水平
arachide
2015-03-14 12:00:27 +08:00
lz身边没明白人

把js搞成莫名奇妙的js了
akong
2015-03-14 19:24:49 +08:00
repeatX ,repeatY未定义吧
akong
2015-03-14 19:50:37 +08:00
this在不用context下指向的对象是不用的,在构造函数指向新建的对象
EXDestroyer
2015-03-14 22:23:32 +08:00
谢谢各位,已经基本弄明白了
whimsySun
2015-03-15 00:16:55 +08:00
第一次见这么写js... 不同改了,全部删掉,先补补js知识重写吧,指不定你后面又写出什么
EXDestroyer
2015-03-15 07:10:23 +08:00
@whimsySun 有哪些问题比较严重的求指出,感谢,说实话自己看书还是悟性还是不够
whimsySun
2015-03-15 23:48:13 +08:00
1. `repeatMap` 完全没有必要作为上下文的函数.
2. 如果`repeatMap`作为构造函数,是不需要`return this`.
3. `js`里声明数据,通常直接使用 `var a = []`; 声明对象`var obd = {}`
4. `flagMatrix[x][y] = new repeatMap(repeatX, repeatY)`这里的`repeatX`和`repeatY`又是什么鬼
EXDestroyer
2015-03-16 00:26:31 +08:00
@whimsySun 谢谢回复,第一个我现在是明白了,2和4的话其实这是一个游戏里面的一小段代码,我没有写明白,第3点我试试优化一些,自己的习惯是不太好

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/176735

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX