<script>
var tree = {};
tree.decorate = function () {
console.log('Make sure the tree won\'t fall');
};tree.getDecorator = function (deco) {
tree[deco].prototype = this;
return new tree[deco];
};tree.BlueBalls = function () {
this.decorate = function () {
this.BlueBalls.prototype.decorate();
console.log('Add blue balls');
}
};tree.getDecorator('BlueBalls').decorate();
</script>或者一些小的实用的代码来阐述这种写法的好处
var tree = {};
tree.decorate = function () {
console.log('Make sure the tree won\'t fall');
};tree.getDecorator = function (deco) {
tree[deco].prototype = this;
return new tree[deco];
};tree.BlueBalls = function () {
this.decorate = function () {
this.BlueBalls.prototype.decorate();
console.log('Add blue balls');
}
};tree.getDecorator('BlueBalls').decorate();
</script>或者一些小的实用的代码来阐述这种写法的好处
有没有可能是因为比如你的代码放在了一个js文件里 这样别人就可以不再写同样的代码而可以直接引用了 这样做的话如果用上述方法一来可以清晰的指明这些方法是用来做什么的 比如有tree则说明是(大概是建一颗动态树之类的吧)那些方法是和tree有关的,二来也可以避免同时引用多个外部文件而导致的命名冲突问题
this.decorate = function () {
this.BlueBalls.prototype.decorate();
console.log('Add blue balls');
}
};这里的this是指tree.BlueBalls 对象,那么this.BlueBalls. 作何解释tree.BlueBalls.BlueBalls ???去掉又报错
另外,看不懂2楼的问题
this.BlueBalls.prototype.decorate();楼主注意这个匿名函数的执行环境,
我把这个this打印出来是tree.BlueBalls 对象,,怎么后面还有.BlueBalls 不理解。。
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Add blue balls
test9.html (第 35 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Add blue balls
test9.html (第 35 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Add blue balls
test9.html (第 35 行)
Make sure the tree won't fall
test9.html (第 21 行)
Make sure the tree won't fall
test9.html (第 21 行)
Add blue balls
test9.html (第 35 行)
Add blue balls
test9.html (第 3汗,我在ff10+firebug的console一看,是这个结果,我也糊涂了,等高手吧。
不会吧,你修改一下,debug看看
tree.BlueBalls = function () {
this.decorate = function () {
if(tree.BlueBalls===this){
console.log('tree BlueBalls is this');
}
this.BlueBalls.prototype.decorate();
console.log('Add blue balls');
}
};
tree.isPrototypeOf(this)返回
true
console.log(this);
this.decorate = function () {
this.BlueBalls.prototype.decorate();
console.log('Add blue balls');
}
};
火狐和谷歌打印的不一样,但是结果是一样的,,昏倒