一、概述
所有函数都有一个属性prototype,是一个对象空间(里面可以存放对应数据),是一个显性原型
隐式原型:__proto__对象空间,可以存储对应数据,每个对象都有。通过对象访问原型
一般使用__proto__访问原型对象,
class Person {
constructor(){
this.age =14;
}
}
Person.prototype.say='hello';
class Son extends Person{
constructor(){
super();
}
}
Son.prototype.activty ='sdhi';
var son =new Son();
console.log(Son.__proto__.__proto__);
console.log(son.__proto____proto__);
如例,使用__proto__可以逐层访问上级的原型或者函数
二、原型链
寻找原型的过程组成的一个链式结构
三、继承------面向对象的三大特性
三大特性:封装:内容抽取
继承:子类继承父类
多态:重写重载
1、 继承的实现
extends:关键词,子类必须有super() (es6)
class Person{
constructor(){
}
}
class Son extends Person{
constructor(){
super()
}
}
原型继承:子类原型对象 = 父类实例对象 看不到继承原型里面的内容,可以调用
function Person() {
}
function Son() {
}
Son.prototype =new Person();
组合继承:对象冒充+原型链继承
function Person() {
this.password ='123'
}
function Son() {
this.password = new Person().password;
}
Son.prototype = new Person();
对象冒充(改this指向),把父的this指向改成指向子
// 对象冒充
function Person() {
this.password ='123';
}
function Son() {
// 改变this指向
Person.call(this)
}
// call自动调用
var son = new Son();
console.log(son.password);
2、多态
子类是父类的多态体现
重写:子类重写父类的方法
重载:同一个方法多个类名(会覆盖)(js没有重载)
重写:子类覆盖(重写)父类的方法 ,打印结果为子类方法
function Person() {
this.sayHello =()=>{
console.log("你好");
}
}
function Son() {
this.sayHello =()=>{
console.log("hello");
}
}
Son.prototype =new Person();
var son = new Son();
// 子类覆盖(重写)父类的方法
console.log(son.sayHello);
三、es6模块化
inport导入(http, data, chrome-extension, edge, https, chrome-untrusted)
export导出
一个内容如果需要导入,必须先导出
export导出
//对象
const obj = {
username:
"jack",
password:'123'
}
//函数
const sayHello = ()=>{
console.log('hello');
}
//值
const message = '这个是一个信息'
//数组
const arr = [1,2,3,4]
//变量的接的数据 需要导出必须用{}
export {
obj,
sayHello,
message,
arr
}
import导入
import {
obj,
sayHello,
message,
arr
} from './export.js' //解构
sayHello()
console.log(`obj`, obj);
console.log(`message`, message);
console.log(`arr`, arr);
引用,使用es6模块化必须要加 type="module"
<script type="module" src="./import.js"></script>
如果直接运行的话会发现报错,看到http, data, chrome-extension, edge, https, chrome-untrusted.会联想到跨域,看其他博主的说法是需要添加服务器,暂时没学到。
Access to script at 'file:///E:/%E5%89%8D%E7%AB%AF/%E5%8D%83%E9%94%8B/JS/%E6%A0%B8%E5%BF%83%E8%AF%AD%E6%B3%95/18day%E5%8E%9F%E5%9E%8B/b.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted.