码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-07-10 01:03:54      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:ble   绑定   div   new   keyword   ack   概念   none   col   

在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的数据都是不同的!!

 

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

标签:ble   绑定   div   new   keyword   ack   概念   none   col   

原文地址:https://www.cnblogs.com/kidsitcn/p/11161396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!