Skip to content

Instantly share code, notes, and snippets.

@guo-yu
Created August 20, 2013 08:39
Show Gist options
  • Save guo-yu/6278806 to your computer and use it in GitHub Desktop.
Save guo-yu/6278806 to your computer and use it in GitHub Desktop.
js prototype 继承实例中的参数问题
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
Copy link

hotoo commented Aug 20, 2013

var Book = function(name) {
    this.name = name;
    this.demo = '123';

    function add(){
      console.log(this)
    }

    var ME = this;
    this.fetch = {};
    this.fetch.add = function(){
      add.apply(ME, arguments);
    };
}


var demo = new Book('123');

// 保持这种API设计风格
demo.fetch.add();

@guo-yu
Copy link
Author

guo-yu 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();

@hotoo
Copy link

hotoo commented Aug 20, 2013

写在一个闭包里就可以了。只是要求 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);
      })
    }
}

@guo-yu
Copy link
Author

guo-yu commented Aug 20, 2013

另外一种方法

不要new 了,new个蛋啊。。。直接在function里把各种原型方法return回去。但大规模实例化的时候会造成内存浪费。。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment