天天看点

javascript Class.method vs Class.prototype.method(类方法和对象方法)

在stackoverflow上看到一个这样的提问,以下代码有什么区别?

Class.method = function () { /* code */ }
Class.prototype.method = function () { /* code using this.values */ }      

看来确实有很多人和我一样对这个问题有疑问,实际上这个牵涉到static和dynamic方法的概念。

Class.method这种模式定义的method是绑定在Class对象之上的。在js中,我们知道一切皆为对象,包括Class(本质上是一个function)。当我们以ClassFunction.method方式定一个一个method时就是在function对象上定义了一个属性而已。这个Class.method和通过new Class()生成的instance没有任何关系,我们可以认为这种Class.method形式为static method.

而第二种Class.prototype.method,我们实际上是在扩展构造函数的prototype功能,它将在通过new Class()生成的每一个object instance上面存在,而在这个instance.method中的this将指向实际调用的object.

看下面的代码加深理解:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();      

注意:将公共的method放到constructorFunction.prototype中去供instance继承,(好处是避免代码的重复,因为如果放到constructorFunction中通过this.method=function(){}的方式去定义,虽然instance.method也可以访问,但是代码是有copy的!!!)而数据则放到constructor function中去定义,这样每一个instance的数据都是不同的!!

转载于:https://www.cnblogs.com/kidsitcn/p/11161396.html

继续阅读