es5中没有类,把函数称作类:
var arr=new Array();
console.log(arr);
__proto__
:原型链。原型链指向当前类的原型对象
自定义一个如上Array函数类:
一个对象的原型链(proto) 指向自身原型对象(prototype)
原型对象的构造函数 指向本身(函数本身)
函数类的原型属性 prototype===函数类的原型对象
/*
* 自定义函数类,写类对象
* */
function myArray(){ //函数指向一个类
this.length=0; //this指向当前函数类的一个对象
}
//当前函数类的原型对象
myArray.prototype={
}
//实例化类对象
var myarr=new myArray();
console.log(myarr)
因为原型对象里未定义:
原型对象包含 构造函数(指向函数类本身)
当前类的原型属性 原型 方法(原型对象上的属性和方法是共享的)
//当前函数类的原型对象
myArray.prototype={
constructor:myArray,
mysort: function () {
//this 指向当前类对象本身(实例本身)
console.log(this); //myArray
}
}
//实例化类对象
var myarr=new myArray();
console.log(myarr); //myArray
myarr.mysort()
可以看到,原型链__proto__指向原型对象prototype里的constructor和mysort
原型对象的构造函数constructor指向默认最高对象Object(函数本身)
原型链结构:
prototype原型对象
原型对象上的属性和方法是共享的
所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法,
Date 对象从 Date.prototype 继承
Array 对象从 Array.prototype 继承
Person 对象从Person.prototype 继承
例子
先学习一下继承:js中的继承
//以人为例
function Person(){
this.name="";
this.job="";
}
Person.prototype={
constructor:Person, //可以默认不写
sex:"",
sleep: function () {
console.log("睡觉");
},
eat: function () {
console.log("吃饭");
}
}
var stu=new Person();
console.log(stu);
赋值:
//以人为例
function Person(name,job){ //类函数 | 构造函数
this.name=name;
this.job=job;
}
Person.prototype={
constructor:Person, //可以默认不写
sex:"",
sleep: function () {
console.log("睡觉");
},
eat: function () {
console.log("吃饭");
}
}
//类在new实例化时 开始执行的是函数的构造
var stu=new Person("小花","学生");
//给对象直接写属性赋值 类似直接在对象的类中新建一个自身属性
stu.sex="男";
console.log(stu);
给对象直接写属性赋值 类似直接在对象的类中新建一个自身属性(不可以)
原型对象属性赋值:(性别一般属于自定义对象)
var stu=new Person("小花","学生");
//原型对象属性赋值
stu.__proto__.sex="女";
console.log(stu);
调用原型对象方法:
//方法一
stu.__proto__.eat();
//方法二
Person.prototype.eat();
关系【面试注意】:
console.log(stu.__proto__ === Person.prototype); //true
//typeOf判断类型 instanceof判断两边类型是否一致
console.log(stu.__proto__ instanceof Person); //false
console.log(typeof stu.__proto__); //object
console.log(stu.__proto__.constructor instanceof Person); //false
console.log(typeof stu.__proto__.constructor); //function