构造函数
定义一个正方形类
function Square(width){
this.width = width;
}
Square.prototype.getArea = function(){
return this.width * this.width;
}
Square.prototype.getLength = function(){
return this.width * 4;
}
let square = new Square(5);
通过上面的代码,简单总结下:
new X()
- 自动创建了空对象
- 自动为空对象关联原型,原型地址指定为
X.prototype - 自动将空对象作为this关键字运行构造函数
- 自动
return this构造函数X() - X函数本身负责给对象本身添加属性
X.prototype对象负责保存对象的共有属性
如何确定一个对象的原型?
你是谁构造的,你的原型就是谁的prototype属性对应的对象。用公式表达为:
对象.__proto__ === 其构造函数.prototype
let x = {}
x.__proto__ === Object.prototype; // true
上面的代码说明:x是由Object构造的,则x的原型就是Object.prototype对应的对象。
类型与类
- 类型是数据的分类,有7种:string, number, symbol, bool, null, undefined, object。
- 类是针对于object的分类,有无数种。官方的有:Array, Function, Date, RegExp等。
一些特殊的对象
- 数组对象
/*命名方法*/
let arr = [1, 2, 3]
let arr = new Array(1, 2, 3) // 元素为1, 2, 3
let arr = new Array(3) // 长度为3的空数组
- 函数对象
/*定义一个函数,几种方法*/
function fn(x, y){return x+y}
let fn2 = function fn(x, y){return x+y}
let fn = (x, y) => {x+y}
let fn = new Function('x', 'y', 'return x+y')