关于JavaScript,肆 (vs Python and Scheme)
JS的对象模型无疑是简单而高效的。从某种意义上来看,简直就是以函数为核心。从面向对象的角度来讲,JS是prototype-based,Python是class-based,Scheme这方面我还未学到啦~我就知道Lisp有个CLOS,还没玩过。
1. 值有类型,变量没有(dynamic typing)。JS中的变量只是名字,这和Scheme一样。Python应该也是,我不是百分百确定。
class C():
pass
D = C
c = C()
C = 1
print C # 1
del C
print D # __main__.C, though C was already deleted from context.
print c # <__main__.C instance at 0x00B44940>
print c.__class__ # __main__.C
2. JS数据类型有numbers, strings, booleans, null, undefined, objects(arrays), functions。new运算符后面可以随便跟个函数,这会创建一个新对象。在此函数内部随便干什么都行,只是这时候this引用的是刚创建的这个对象。
function f() { this.a = 2 }
f.a = 1 // f的property
alert(f)
alert(f.a) // 1
f = new f() // 创建对象,覆盖名字f
alert(f) // 新对象
alert(f.a) // 执行f()时加上的property a, 值为2
被创建的对象(objects/arrays, functions)可以随意在运行时添加properties(其内部实现应该是hashtable)。如果一个property类型为函数,并且从该对象被调用,函数中的this就是此对象:
function f() { alert(this.a) }
o = Object()
o.a = 'a in the new object'
o.method = f
o.method() // 'a in the new object'
f2 = o.method // f2 is equal to f, just a plain function
f2() // "this" refers to window object now, so "a" is not defined
如果你在全局scope定义一个函数,这个函数可被视为global object的一个方法。所以在JS中function和method真的是没什么本质区别的。
Python的数据类型见这里:http://docs.python.org/ref/types.html
下面这段代码很能说明Python中function和method还是有区别的:
class C():
""" A dummy boring class. """
C.g = lambda self: 'method'
# unbound method
print C.g
print C.g(C())
# bound method
c = C()
print c.g
print c.g()
# changed method, still bound
c.__class__.g = lambda self: 'changed method'
print c.g
print c.g()
# function
c.g = lambda : 'function'
print c.g
print c.g()