JS对象模型
JavaScript 是一种基于原型(Prototype)的面向对象语言,而不是基于类的面向对象语言。
C++、Java有类Class和实例Instance的概念,类是一类事物的抽象,而实例则是类的实体。
JS是基于原型的语言,它只有原型对象的概念。原型对象就是一个模板,新的对象从这个模板构建从而获取最初的属性。任何对象在运行时可以动态的增加属性。而且,任何一个对象都可以作为另一个对象的原型,这样后者就可以共享前者的属性
定义类
字面式声明方式
var obj = {
x: 1,
1: 'abc',
"y": '123'
}
for (let x in obj)
console.log(x, typeof x);
/*运行结果:
1 string
x string
y string
*/
这种方法称作字面值创建对象
let a = 1, b = 2
let obj = {
a, b}
let obj1 = {
a: a, 'b': b} // 引号可以省去
console.log(obj)
console.log(obj1)
let c = 'str1'
let d = {
c: 100, // 这个c是字符串'c', 不是上面的变量c
[c]: 200 // 如果使用c变量, 就要用中括号括起来
}
console.log(d)
/*运行结果:
{ a: 1, b: 2 }
{ a: 1, b: 2 }
{ c: 100, str1: 200 }
*/
对象的键key只能是字符串类型, 如果使用变量, 用中括号[]
括起来
ES6之前的构造器
1、定义一个函数(构造器)对象,函数名首字母大写
2、使用this定义属性
3、使用new和构造器创建一个新对象
function Point(x, y) {
this.x = x;
this.y = y;
this.show = () => console.log(this.x, this.y);
console.log('Point ----')
}
p1 = new Point(3, 4)
console.log(p1)
console.log('--'.repeat(20))
function PointChild(x, y, z) {
Point.call(this, x, y) // 继承
this.z = z
console.log('PointChild ---')
}
p2 = new PointChild(4, 5, 6)
console.log(p2)
p2.show()
/*运行结果:
Point ----
Point { x: 3, y: 4, show: [Function] }
----------------------------------------
Point ----
PointChild ---
PointChild { x: 4, y: 5, show: [Function], z: 6 }
4 5
*/
构建一个新的对象必须用new来构建, 类中调用基类使用call方法, 可以传入子类的this
注意:如果不使用new关键字,就是一次普通的函数调用,this不代表实例
ES6中的class
从ES6开始,新提供了class关键字,使得创建对象更加简单、清晰。
1、类定义使用class关键字。创建的本质上还是函数,是一个特殊的函数
2、一个类只能拥有一个名为constructor的构造器方法。如果没有显式的定义一个构造方法,则会添加一个默认的constuctor方法。
3、继承使用extends关键字
4、一个构造器可以使用super关键字来调用一个父类的构造函数
5、类没有私有属性
class Point {
constructor(x, y){
// 构造器
this.x = x;
this.y = y;
}
show() {
//方法
console.log(this, this.x, this.y);
}
}
p1 = new Point(2,3