使用Knockout.js继承

Vim*_*987 2 javascript inheritance knockout.js

我有一些像这样的代码:

var A = function(a,b,c) {
  var self = this;
  self.a = ko.observable(a);
  ... 


  self.function1 = ko.computed(function () {
      dothing(a);
      ...
  } 

  self.function2 = ko.computed(function () {
      dothing(b);
      ...
  }
}

var B = function(a,b,c,d) {
    var self = this;
  self.a = ko.observable(a);
  ... 


  self.function1 = ko.computed(function () {
      dothing(a);
      ...
  } 

  self.function2 = ko.computed(function () {
      dothing(b);
      ...
  }
}
Run Code Online (Sandbox Code Playgroud)

如何将function1和function2"提取"到A和B可以共享的功能?

Eli*_*gem 5

这就是原型适合的地方:

function AB()
{};//empty object
AB.prototype.function1 = function()
{
    var self = this;//doesn't have access to self, but `this` will point to either A or B
    //do stuff
};
var A = function()
{
    var self = this;//constructor
}
var B = function()
{
    var self = this;//constructor
}
A.prototype = new AB;
A.prototype.constructor = A;
B.prototype = new AB;
B.prototype.constructor = B;
//marginally shorter:
A.prototype = B.prototype = new AB;
A.prototype.constructor = A;
B.prototype.constructor = B;
//instances:
var foo = new A();
var bar = new B();
console.log(foo.function1 === bar.function1);//logs true
Run Code Online (Sandbox Code Playgroud)

话虽如此,我个人更喜欢定期定义我的构造函数:

function A()
{
    var self = this;
}
foo = new A();
console.log(Object.getPrototypeOf(foo).constructor.name);//logs A
Run Code Online (Sandbox Code Playgroud)

而您的代码为变量分配了一个匿名函数,这意味着构造函数没有名称:

foo = new A();
console.log(Object.getPrototypeOf(foo).constructor.name);//logs ''
Run Code Online (Sandbox Code Playgroud)

这并不是什么大不了的事,但只是让你知道...


从全局(或任何其他)范围引用方法:

var virtualNewFunction = new A();//create object
virtualNewFunction = virtualNewFunction.function1;//virtualNewFunction now references function1
virtualNewFunction();
Run Code Online (Sandbox Code Playgroud)

关闭将是可访问的(暴露),但仍然非常小心this:

A = function()
{
    var self = this;
    this.function1 = function()
    {
        console.log(this);
        console.log(self);
    };
}
foo = new A();
foo.function1();//logs A twice
foo = foo.function1
foo();//logs this -> window! self => A
Run Code Online (Sandbox Code Playgroud)

另一种可能性是"借用"一个功能:

A = function()
{
    var self = this;
    this.function1 = function()
    {
        console.log(this);
        console.log(self);
    };
}
B = function()
{//no method
    var self = this;
}
foo = new A();
bar = new B();
foo.function1.apply(bar,[]);//call as though function1 was method of B
Run Code Online (Sandbox Code Playgroud)

再次,要小心:在这种情况下,this日志B,但self仍然参考A!你可以建立某些"安全网":

    this.function1 = function()
    {
        self = this !== window && this !== self ? this : self;//redefine self to current caller object, unless it's window 
        console.log(this);
        console.log(self);
    };
Run Code Online (Sandbox Code Playgroud)

但老实说,你可能会很好地阅读这个操作符来掌握所有这些引用技巧.一旦掌握了基础知识,就不那么难了.同时检查调用应用方法以获取有关如何"共享/借用"方法的更多详细信息