JavaScript的所有数据都可以看成对象,那是不是我们已经在使用面向对象编程了呢?
当然不是。如果我们只使用Number、Array、string以及基本的{...}定义的对象,还无法发挥出面向对象编程的威力。
JavaScript的面向对象编程和大多数其他语言如Java、C#的面向对象编程都不太一样。如果你熟悉Java或C#,很好,你一定明白面向对象的两个基本概念:
类:类是对象的类型模板,例如,定义Student类来表示学生,类本身是一种类型,Student表示学生类型,但不表示任何具体的某个学生;
实例:实例是根据类创建的对象,例如,根据Student类可以创建出xiaoming、xiaohong、xiaojun等多个实例,每个实例表示一个具体的学生,他们全都属于Student类型。
所以,类和实例是大多数面向对象编程语言的基本概念。不过,在JavaScript中,这个概念需要改一改。JavaScript不区分类和实例的概念,而是通过原型(prototype)来实现面向对象编程。 -《廖雪峰JS教程》
上面的解释我觉得很到位,这里就不再多讲了,直接上代码(代码就是最好的文档,网上有人说为什么开源项目的文档没多少看,其实那是因为能看懂代码的人都直接看代码了_):
//js 会给每个创建的对象设置一个原型,指向它的原型对象
var arr=[1,2,3];
/**
* arr对象 其原型对象就是Array,因此js中存在着原型链,arr ----> Array.prototype ----> Object.prototype ----> null
*
* 由于js定义了Array.prototype中定义了sort(),indexof()等方法,因此你可以在所有的Array对象上直接调用这些方法。所以可以arr.sort();
*/
/**
* 在js中函数也是对象。因此函数也有自己的原型链
*/
function student() {
console.log('测试');
}
// student->Function.prototype->Object.prototype->null
//js 创建对象主要由以下两种方法
//方法一 通过{...}
var zhaotong={
name:'zhaotong',
age:23,
hello:function () {
console.log(`${this.name} 是 ${this.age} 岁 `);
}
};
zhaotong.hello();
//方法二 通过new 关键字来创建
function Student(name) {
this.name=name;
this.hello=function () {
console.log(`我是${this.name}`);
}
};
var zhaotong1=new Student('zhaotong1');
var zhaotong2=new Student('zhaotong2');
zhaotong1.hello();
zhaotong2.hello();
//这里大家会发现,我们每次去重新创建一个学生对象,都会去创建一个hello方法,虽然代码都是一样的,但他们确实两个不同的函数
//其实这么多对象只需要共享一个hello函数即可,因此根据对象查找原则,我们将hello方法放在Student对象上,便可以实现共享
Student.prototype.hello=function(){
console.log(`我是${this.name}`);
}
//此外用new创建的对象,还从其原型对象上获得了一个constructor 属性,它门指向Student对象本身
console.log(zhaotong1.constructor==Student.prototype.constructor);//true
console.log(Student.prototype.constructor==Student);//true
console.log(Object.getPrototypeOf(zhaotong1)==Student.prototype);//true
console.log(zhaotong1 instanceof Student);//true
//下面的一个例子是在廖雪峰老师的教程中看到的一个写法,个人感觉很好,特此记录。
function Teacher(props) {
this.name=props.name||'no-name';
this.age=props.age||23
}
Teacher.prototype.hello=function (){
console.log(`${this.name}是${this.age}岁!`);
};
function createTeacher(props) {
return new Teacher(props||{})
}
var zhaotong3=createTeacher({name:'zhaotong'});
zhaotong3.hello();
上面代码的运行结果如下