简单学Javascript的对象

2015-08-23  本文已影响32人  chenge微博谈

这个部分是js最重要的部分,也是最难掌握的部分。最近看到一本书《Speaking Javascript》, 分四层讲解,感觉很有效。

Chapter 17. Objects and Inheritance

There are several layers to object-oriented programming (OOP) in JavaScript:
Layer 1: Object-orientation with single objects (covered in Layer 1: 单个对象)
Layer 2: Prototype chains of objects (described in Layer 2: 原型链)
Layer 3: Constructors as factories for instances, similar to classes in other languages (discussed in Layer 3: 构造函数)
Layer 4: Subclassing, creating new constructors by inheriting from existing ones (covered in Layer 4: 基于构造函数的继承)

前三层

我这里分享下前三层的一点浅见,第四层我留待以后再探讨。

1 单个对象

calc = {
    add: function(x, y){
        return x + y
    }
}

console.log(calc.add(1, 3))

这个非常简单直观。

2 原型链

这个是js特立独行的地方:

对象————>原型

代码示例如下:

calc2 = Object.create(calc)
calc2.sub = function(x, y){
    return x - y
}

console.log(calc2.add(1, 3))
console.log(calc2.sub(1, 3))

create方法建立了原型链的关系,calc2扩展了sub方法,也有继承的意味,代码也很容易理解吧。

3 构造函数

构造函数是很多书介绍的方式,稍微复杂一些

function Calc(){

}

Calc.prototype.add = function(x, y){
    return x + y
}

aCalc = new Calc()
console.log(aCalc.add(2, 3))

总结

上一篇 下一篇

猜你喜欢

热点阅读