Created
August 20, 2013 08:39
-
-
Save guo-yu/6278806 to your computer and use it in GitHub Desktop.
js prototype 继承实例中的参数问题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Book = function(name) { | |
this.name = name; | |
this.demo = '123'; | |
} | |
var Method = function() { | |
// 继承了 Book 的静态属性 this.demo = '123' | |
Book.apply(this, arguments); | |
} | |
Method.prototype.add = function() { | |
// 如何访问到 demo 这个实例中的东西呢? | |
console.log(this); | |
} | |
Book.prototype.fetch = new Method(); | |
var demo = new Book('123'); | |
// 保持这种API设计风格 | |
demo.fetch.add(); |
hotoo
commented
Aug 20, 2013
一种挫逼解决方案
var Method = function(params) {
if (params) this.parent = params;
}
var Book = function(name) {
this.name = name;
this.demo = '123';
// 将实例化 Method 的语句写在Book中,传入this
Book.prototype.fetch = new Method(this);
}
Method.prototype.add = function() {
// 如何访问到 demo 这个实例中的东西呢?
console.log(this);
}
var demo = new Book('123');
// 保持这种API设计风格
demo.fetch.add();
写在一个闭包里就可以了。只是要求 demo.fetch.add() 这样的 api 的话,还可以简单点:
var Book = function(name) {
this.name = name;
this.demo = '123';
var ME = this;
this.fetch = {};
this.fetch.add = function(){
// 用 ME 替代 this
};
// 或者用
this.fetch = {
add: Function.createDelegate(this, function(){
console.log(this);
})
}
}
另外一种方法
不要new 了,new个蛋啊。。。直接在function里把各种原型方法return回去。但大规模实例化的时候会造成内存浪费。。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment