原型对象和原型链

1-1 原型

以数组为例,数组有shift,unshift,push,pop等等,我们之所能够使用这些方向,是因为它的原型上定义了这些方法

1-2 JS为什么会有原型

Javascript的继承,是基于原型的继承。

1-3 类和对象

类:就是具有一类相同特征的事物的抽象。
对象:某类事物具体的实例。

1-3-1 使用构造函数模拟一个类

1-1 它有两个自有属性
1-2 在原型对象上挂载了sayName,之后所有的实例对象都共享了该方法。
function Person(name,age){
this.name = name;
this.age = age;
}
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayName = function(){
console.log(this.name)
}
var p = new Person(“cheng”,18);
p.sayName()
构造函数的特点
1.首字母大写
2.函数内部使用this关键字,this指向实例化的对象
3.可以this关键字给对象添加属性
4.使用new关键字实例化一个对象。

1-4 原型链 以数组为例

var arr = [1,2,3];
console.log(arr.proto)
console.log(arr.proto==Array.prototype); //true
console.log(arr.proto.proto)
console.log(arr.proto.proto == Object.prototype) //true;
console.log(arr.proto.proto.proto) //null;
原型对象和原型链 - 图1

1-5 私有属性和共有属性

var obj = {
name:”cheng”,
age:18
}
Object.prototype.sex =”男”
console.log(obj.hasOwnProperty(“sex”))