2016年4月11日星期一

javascript必知必会之prototype

离考试还有半个小时,温故知新js的prototype,遇到此文,分享之. 原文链接

但是最后讲的函数自身声明的方法与prototype添加的方法,比较不是特别清楚.

javascript必知必会之prototype

本博客所有内容采用 Creative Commons Licenses 许可使用. 引用本内容时,请保留 朱涛, 出处 ,并且 非商业 .
点击 RSS 进行订阅.(推荐使用 google reader, 如果你的浏览器不支持直接订阅, 请直接在 google reader 中手动添加).

摘要

本系列博文主要谈一些在 javascript 使用中经常会混淆的高级应用,包括: prototype, closure, scope, this关键字. 对于一个需要提高自己javascript水平的程序员,这些都是必须要掌握的.
本节主要介绍prototype.

起由

最近在做一个项目,里面大量地使用 javascript 作为页面的动态生成脚本, 使用 json 与服务器进行通信. 在读之前遗留的代码时, 经常会弄不清楚, 作用域, this关键字在当前context下的指向等,于是便开始专门学习了 相关的知识,记录下来与大家分享.
下面的内容中会有一些代码,建议大家也去尝试修改和理解,这样更容易掌握. 点击 这儿 下载所涉及到的源码.

prototype

javascript 是一种 prototype based programming 的语言, 而与我们通常的 class based programming 有很大 的区别,我列举重要的几点如下:
  1. 函数是first class object, 也就是说函数与对象具有相同的语言地位
  2. 没有类,只有对象
  3. 函数也是一种对象,所谓的函数对象
  4. 对象是按 引用 来传递的
那么这种 prototype based programming 的语言如何实现继承呢(OO的一大基本要素), 这也便是 prototype 的由来.
看下面的代码片断:
function foo(a, b, c)
{
return a*b*c;
}
alert(foo.length);
alert(typeof foo.constructor);
alert(typeof foo.call);
alert(typeof foo.apply);
alert(typeof foo.prototype);
对于上面的代码,用浏览器运行后你会发现:
  1. length: 提供的是函数的参数个数
  2. prototype: 是一个object
  3. 其它三个都是function
而对于任何一个函数的声明,它都将会具有上面所述的5个property(方法或者属性).
下面我们主要看下prototype.
// prototype
function Person(name, gender)
{
this.name = name;
this.gender = gender;
this.whoAreYou = function(){//这个也是所谓的closure, 内部函数可以访问外部函数的变量
var res = "I'm " + this.name + " and I'm a " + this.gender +".";
return res;
};
}
// 那么在由Person创建的对象便具有了下面的几个属性
Person.prototype.age = 24;
Person.prototype.getAge = function(){
return this.age;
};
flag = true;
if (flag)
{
var fun = new Person("Tower", "male");
alert(fun.name);
alert(fun.gender);
alert(fun.whoAreYou());
alert(fun.getAge());
}
Person.prototype.salary = 10000;
Person.prototype.getSalary = function(){
return this.name + " can earn about " + this.salary + "RMB each month." ;
};
// 下面就是最神奇的地方, 我们改变了Person的prototype,而这个改变是在创建fun之后
// 而这个改变使得fun也具有了相同的属性和方法
// 继承的意味即此
if (flag)
{
alert(fun.getSalary());
alert(fun.constructor.prototype.age);//而这个相当于你直接调用 Person.prototype.age
alert(Person.prototype.age);
}
从上面的示例中我们可以发现,对于prototype的方法或者属性,我们可以 动态地 增加, 而由其创建的 对象自动会 继承 相关的方法和属性.
另外,每个对象都有一个 constructor 属性,用于指向创建其的函数对象,如上例中的 fun.constructor 指向的 就是 Person.
那么一个疑问就自然产生了, 函数对象中自身声明的方法和属性与prototype声明的对象有什么差别?
有下面几个差别:
  1. 自身声明的方法和属性是 静态的, 也就是说你在声明后,试图再去增加新的方法或者修改已有的方法,并不会 对由其创建的对象产生影响, 也即 继承 失败
  2. 而prototype可以动态地增加新的方法或者修改已有的方法, 从而是 动态的 ,一旦 父函数对象 声明了相关 的prototype属性,由其创建的对象会 自动继承 这些prototype的属性.
继续上面的例子:
flag = true;
// 函数内部声明的方法是静态的,无法传递的
Person.school = "ISCAS";
Person.whoAreYou = function(){
return "zhutao";
};//动态更改声明期的方法,并不会影响由其创建的对象的方法, 即所谓的 静态
if (flag)
{
alert(Person.school);
alert(fun.school);//输出的是 "undefined"
alert(Person.whoAreYou()); //输出 zhutao
alert(fun.whoAreYou()); // I'm Tower and I'm a male.
}
Person.prototype.getSalary = function(){
return "I can earn 1000000 USD";
};
if (flag)
{
alert(fun.getSalary());//已经继承了改变, 即所谓的 动态
}
既然有函数对象本身的属性, 也有prototype的属性, 那么是由其创建的对象是如何搜索相应的属性的呢?
基本是按照下面的流程和顺序来进行.
  1. 先去搜索函数对象本身的属性,如果找到立即执行
  2. 如果1没有找到,则会去搜索prototype属性,有2种结果,找到则直接执行,否则继续搜索 父对象 的 父对象 的prototype, 直至找到,或者到达 prototype chain 的结尾(结尾会是Object对象)
上面也回答如果函数对象本身的属性与prototype属性相同(重名)时的解决方式, 函数本身的对象 优先 .
再看一个多重prototype链的例子:
// 多重prototype链的例子
function Employee(name)
{
this.name = "";
this.dept = "general";
this.gender = "unknown";
}
function WorkerBee()
{
this.projects = [];
this.hasCar = false;
}
WorkerBee.prototype = new Employee; // 第一层prototype链
function Engineer()
{
this.dept = "engineer"; //覆盖了 "父对象"
this.language = "javascript";
}
Engineer.prototype = new WorkerBee; // 第二层prototype链
var jay = new Engineer("Jay");
if (flag)
{
alert(jay.dept);    //engineer, 找到的是自己的属性
alert(jay.hasCar);  // false, 搜索到的是自己上一层的属性
alert(jay.gender);  // unknown, 搜索到的是自己上二层的属性
}
上面这个示例的对象关系如下:
http://farm3.static.flickr.com/2585/3933273719_ccab4562d2.jpg

结论

javascript 的prototype给语言本身增加了很强的灵活性,但与 class based programming 相比整个思维逻辑还是有很大的不同,所以需要更多地思考和揣摩.
而 javascript是披着c语言外衣的函数式语言 的理解自然也需要更多地思考.
下一节我会继续讨论下 javascript 的另一个重要而且比较容易弄错的知识 closure.
欢迎大家留言讨论.

2016年3月23日星期三

Emacs配置文件更新-增加对OCaml的支持

自从fork了purcell大神的emacs配置, 着实学习了很多很多. 优化的init.el, lisp配置方式让我彻底学习了什么叫做好的优化的有序的emacs lisp方言配置. 大神的配置对前端语言支持很好, 因为课程需要, 我的OCaml用不了了. 于是, 站在大神的肩膀上, 尝试着新方式来配置OCaml(tuareg)

先说下以前的配置, 在根目录的.emacs里, 简单粗暴地写上如下几句, 大意是设置加载文件位置, 调用三个OCaml的插件 - 都在tuareg文件夹了.


  1. ~/.emacs
  2. (add-to-list 'load-path "DIR")
  3. (require 'tuareg)
  4. (require 'ocamldebug)
  5. (require 'tuareg_indent)

  6. (setq auto-mode-alist (cons '("\\.ml\\w?" . tuareg-mode) auto-mode-alist))
  7. (autoload 'tuareg-mode "tuareg" "Major mode for editing Caml code" t)
  8. (autoload 'camldebug "camldebug" "Run the Caml debugger" t)

然后现在这样就不好使了, 我的文件结构更新如下了,

  1. ~/.emacs.d/
  2. init.el #Emacs会自动从init.el开始执行
  3. elpa/ #通过ELPA下载的插件所保存的位置
  4. lisp/ #就是加载各个插件的初始化文件的位置啦
  5. init-xxx.el #某初始化文件,如init-sql.el
  6. .....

以前的.emacs单一文件被init.el初始化文件代替, 其中require lisp/目录下的具体的插件配置. 相应的, 为了配置OCaml编译环境, 我应该在init.el里加入 (require 'init-ocaml), 然后在lisp/文件夹下新建init-ocaml.el空白文件, 填补上如下代码.

  1. ;;~/.emacs.d/lisp/init-ocaml
  2. (add-to-list 'load-path
  3. (expand-file-name "lisp/tuareg" user-emacs-directory))
  4. (require 'tuareg)
  5. (require 'ocamldebug)
  6. (require 'tuareg_indent)
  7. (setq auto-mode-alist (cons '("\\.ml\\w?" . tuareg-mode) auto-mode-alist))
  8. (autoload 'tuareg-mode "tuareg" "Major mode for editing Caml code" t)
  9. (autoload 'camldebug "camldebug" "Run the Caml debugger" t)

  10. (provide 'init-ocaml)

也是设置load-path, 注意我们的OCaml配置文件不仅仅只有tuareg.el, ocamldebug.el, tuareg_indent.el这三个, 其背后依赖的是一个名为tuareg的package, 将其整体放进lisp文件夹中即可.

好了, 大功告成, 打开熟悉的.ml后缀文件, 语法高亮, tuareg插件全部都回来啦, 开心! 

同时, 我有另外一个疑问, 这里调用的Package是我自己复制粘贴进去的, 与elpa包管理器下载的有什么区别呢? 仔细看了下文件结构, 我有些明白了,


  • ~/.emacs.d/
  • init.el #Emacs会自动从init.el开始执行
  • elpa/ #通过ELPA下载的插件所保存的位置
  • tadauto-complete-20160310.2248/
  • ....
  • lisp/ #就是加载各个插件的初始化文件的位置啦
  • init-xxx.el #某初始化文件,如init-sql.el
  • tuareg/

  • 重新祭上文件结构, lisp里的init - xxx.el配置文件配置了插件,require等, 其中包括epla信息, 故插件包都会通过epla管理下载在elpa/文件夹里. 本篇文章中, 我是手动下载并配置了插件包, 绕过elpa, 将其放进lisp文件夹里. 在Emacs24以后, elpa的引入极大地实现了配置文件的轻量化, 传统的(可能会庞大的)插件包不需要备份, 换电脑换设备Emacs初始化时会自动执行下载elpa的命令, 下载最新的插件包. 这里边的学问还是很大呢.

    不说了, 赶工OCaml编译器去了.

    2016年3月15日星期二

    解决apt-get依赖(unmet dependencies)问题

    好几个月没开steam,想上商店看看,可是启动steam就报错,

    You are missing the following 32-bit libraries, and Steam may not run: libGL.so.1

    按照这篇帖子,一步一步解决问题,最后一步又卡了壳,

    * 解决steam报错找不到libGL.so.1问题方案,


    1- If you haven't updated your computer in a while, 
    copy (ctrl+c) and paste (ctrl+SHIFT+v) this (and then hit enter to run it). If you don't know what this is, just do it. :
    Code:
    sudo apt-get update && sudo apt-get -y upgrade
    2- If you've installed Steam already, skip to step 3. If you haven't installed Steam, open Terminal with ctrl+alt+t. Then copy (ctrl+c) and paste (ctrl+SHIFT+v) this (and then hit enter to run it):
    Code:
    sudo apt-get install -y steam
    3- Now for the fix. Copy (ctrl+c) and paste (ctrl+SHIFT+v) this to edit Steam's configuration file (and then hit enter to run it):
    Code:
    sudo nano /etc/ld.so.conf.d/steam.conf
    4- It'll probably be blank. If it's blank, paste these two lines. If it's not blank, just paste these two lines to the very bottom. Copy (ctrl+c) and paste (ctrl+SHIFT+v) this (and then enter to run it):
    Code:
    /usr/lib32
    /usr/lib/i386-linux-gnu/mesa
    5- Save it by hitting ctrl-x, then y, then enter.

    6- Now copy (ctrl+c) and paste (ctrl+SHIFT+v) this (and then hit enter to run it).:
    Code:
    sudo ldconfig
    7- Finally, copy (ctrl+c) and paste (ctrl+SHIFT+v) this (and then hit enter to run it). It reinstalls a Mesa/OpenGL library:
    Code:
    sudo apt-get install --reinstall libgl1-mesa-glx:i386
    8- Open Steam, download Team Fortress 2, and go kill some folks.


    可是到了如上第七步骤的时候,有错误啦,

    The following packages have unmet dependencies:
    .................

    二逼如我,按照依赖的package名字,挨行敲入

    sudo apt-get install PACKAGENAME

    可总是有如下类似错误,即安装不成功

    0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded

    然后Google一番,终于找到了解决方案,

    * 无敌神龙命令出来啦!

    sudo apt-get -o Debug::pkgProblemResolver=yes dist-upgrade

    自动修复这个依赖问题,自动安装缺失的包。太棒了。

    至于更多的apt-get参考这篇帖子,解释的非常翔实。

    解决apt-get update失败提示Unable to connect to 127.0.0.1问题

    这半个月来,隔三差五的想起来一下sudo apt-get update,就是提示失败,满屏的,

    Err http://ph.archive.ubuntu.com precise Release.gpg                           
      Unable to connect to ph.archive.ubuntu.com:http: [IP: X.X.X.X 80]
    Err http://ph.archive.ubuntu.com precise-updates Release.gpg            
      Unable to connect to ph.archive.ubuntu.com:http: [IP: X.X.X.X 80]
    。。。。。
    
    W: Failed to fetch http://fr.archive.ubuntu.com/ubuntu/dists/precise/InRelease  
    。。。。。。。。。
    W: Some index files failed to download. They have been ignored, or old ones used instead.


    重要提示在这里,

      ............Unable to connect to 127.0.0.1:1080:

    端口是1080,看到这里我明白了些许。前段时间回国用shadowsocks来翻墙,里边的代理信息就是通过的1080端口,google了一下,我这样奇葩的问题比较少见。整理一下思路,我需要重置下1080端口,取消代理设置。

    1. 删除shadowsocks配置信息,没什么卵用 -> 彻底remove掉shadowsocks,还是没什么卵用

    2. 更改127.0.0.1这个DNS,用8.8.8.8,还是没什么卵用

    3. 最终误打误打还是解决了问题----->

         sudo apt-get install 
       sudo apt-get autoremove


    所以呢,现在正在谷歌apt-get各种命令来看...