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

最新文章

  1. PM(Project Manager):系列博客
  2. genymotion是一款完全超越BlueStacks
  3. js 鼠标事件的抓取代码
  4. Flex中 Array 的IndexOf 的作用
  5. 第三十八篇、给UITabBar按钮的动画效果
  6. 从零学起PHP
  7. crawler_httpclient代理访问
  8. JAVA入门[4]-IntelliJ IDEA配置Tomcat
  9. 知识点练习day9
  10. 面向对象的JavaScript-小结
  11. mac 环境搭建
  12. python 二分查找法
  13. C# http请求带请求头部分
  14. Object的wait/notify/notifyAll&&Thread的sleep/yield/join/holdsLock
  15. POJ2387(dijkstra堆优化)
  16. char、varchar、nchar、nvarchar特点比较
  17. 第二版_TestNG+Excel+(HTTP+JSON) 简单接口测试
  18. stl空间配置器简介
  19. sharepoint 配置个人网站容量
  20. Codeforces Round #358 (Div. 2) C. Alyona and the Tree dfs

热门文章

  1. Lua语法要点2
  2. HLOJ1361 Walking on the Grid II 矩阵快速幂
  3. Python实现感知器的逻辑电路(与门、与非门、或门、异或门)
  4. html-前端内容初识
  5. HTML基础一-html、CSS
  6. Codeforces Round 564 题解
  7. Spring事务注解@Transactional失效的问题
  8. Mac-搭建Hadoop集群
  9. 使用vue搭建应用五引入Mock.js
  10. DDD框架基础知识