快速浏览一下JavaScript,发现它还是和c++这类传统一点的语言有很大不同。本文着重描述一下custom Object和inheritance(我是JavaScript新手,没有用过JavaScript)
我不喜欢开门见山,所以我想一点点地举例,引入说明这两个问题。
1、JavaScript中的类型系统
JavaScript中有五种类型的变量:boolean, number, string, object, function。有趣吧,function也是一种类型。
在JavaScript中,一切皆对象。这和Python的思想是一样的。看来这类动态脚本语言都是差不多的。
1.3333333.toFixed(2) // ’1.33’ 7..toString() // ’7’
typeof 1. // ’number’ typeof new Number(1.) // ’object’ typeof new String(’Hi!’) // ’object’
function f(x) { return f.A x * x } f.A = 2.7 function Buffer() {} Buffer.MAX_LINE_LENGTH = 4096
2、 对象和函数
对象创建有两种方法:对象文字和new运算符
使用对象文字创建对象:
var p = { x: 0.1, y: 0.2 }
’z’ in p // false p.z = 0.3 // introduce new property ’z’ ’z’ in p // true delete p.z // remove ’z’ from p p.z // undefined
p.move = function(x, y) { this.x = x this.y = y } p.move(1, 1) // invoke a method
创建对象的第二种方法就是使用new运算符,new后面跟着构造函数。
var p = new Object p.x = 0.1 p.y = 0.2
这个new运算符分配空间给新的对象,并且调用所给出的构造函数(这里就是Object构造函数)初始化这个对象。构造函数传递新创建的对象作为隐含的this参数。
在JavaScript中没有类这个概念,但是有构造函数。通常,构造函数的首字母大写,用来区分普通的函数:
function Point(x, y) { this.x = x this.y = y } var p = new Point(1, 2)
function Point(x, y) { this.x = x this.y = y } Point.prototype = new Object // can be omitted here Point.prototype.translate = function(dx, dy) { this.x += dx this.y += dy }
var p0 = new Point(1, 1) var p1 = new Point(0, 1) p1.translate(1, -1) p0 === p1 // false p0.translate === p1.translate // true
下面我们使用构造函数进行继承:
function Point(x, y) { this.x = x this.y = y } Point.prototype = { move: function(x, y) { this.x = x this.y = y }, translate: function(dx, dy) { this.x += dx this.y += dy }, area: function() { return 0; } } function Ellipsis(x, y, a, b) { Point.call(this, x, y) this.a = a this.b = b } Ellipsis.prototype = new Point Ellipsis.prototype.area = function() { return Math.PI this.a * this.b; } function Circle(x, y, r) { Ellipsis.call(this, x, y, r, r) } Circle.prototype = new Ellipsis
var circle = new Circle(0, 0, 1) circle.move(1, 1)
4、JavaScript中的数据封装。
function Point(x, y) { this.getX = function() { return x; } this.setX = function(x2) { x = x2; } this.getY = function() { return y; } this.setY = function(y2) { y = y2; } }
当Point构造函数被调用时,对象创建了get方法和set方法。在这两个方法的作用域内可以可以访问Point构造函数的作用域内的x和y成员。只有getter和setter才能访问x,y,除此之外别无他法。这就是JavaScript中的私有成员机制,表现出了数据封装的作用。