一、对象
1·、 对象创建
- Object构造函数 let obj=new Object();适用于对象内容不确定场景代码冗余
- 对象字面量 使用{},代码冗余
- 工厂函数 :创建的对象无法都显示为Object,无法显示具体类型
function creatObj(name,age){
let obj={name:name,age:age,sayName:function(){console.log(name)}}
return obj}
- 自定义构造函数,缺点:创建多个函数
function Person(name,age){
this.name=name;
this.age=age;
this.sayName=function(){
console.log(this.name)}
}
let p = new Person('tom',12)
- 自定义构造函数+原型,可显示具体类型,为了解决创建多个对象实例会创建多个对象方法的问题,可将公共方法添加到prototype(显式原型)1.当使用了构造函数,并且new 构造函数(),后台会隐式执行new Object()创建对象;2.将构造函数的作用域给新对象,(即new Object()创建出的对象),而函数体内的this就代表new Object()出来的对象。3.执行构造函数的代码。4.返回新对象(后台直接返回);
function Person(name,age){
this.name=name;
this.age=age;}
Person.prototype.sayName = function(){console.log(this.name)}
let p = new Person('tom',12)
- 隐式原型__proto__ 每个对象都有,实例对象的__proto__指向其构造函数的prototype,所有函数的__proto__都相等,指向Function.prototype
- instanceof 检测对象实例是否属于构造函数
- 显式原型prototype 函数创建时默认添加prototype属性,初始值为空对象
- hasOwnProperty 检测对象本身是否含有某属性,不包含原型链
- ES6 Class constructor构造函数非必须成员属性语法,必须使用es6fun(){}不能使用fun:function(){}
class Person{
constructor(name,age)
{this.name=name;this.age=age;}
sayName(){console.log(this.name)
}
}
2、继承
- 原型链继承,可以使用父对象的方法
function Super(){this.superPer = 'super'}
Super.prototype.saySuper=function(){console.log(this.superPer)}
function Sub(){this.subPer = 'sub'}
Sub.prototype=new Super()
Sub.prototype.constructor = Sub;
Sub.prototype.saySub=function(){console.log(this.subPer )}
- 借用构造函数(伪继承),可以使用父对象的属性
function Super(name){this.name=namethis.superPer = 'super'}
function Sub(name,age){
Super.call(this,name)
this.age= age;
}
- 组合继承,既可以使用对象方法,又可以使用对象属性
function Super(name){
this.name=name;
this.superPer = 'super'}
Super.prototype.saySuper=function(){console.log(this.name)}
function Sub(name,age){
Super.call(this,name)
this.age= age;}
Sub.prototype=new Super()
Sub.prototype.constructor = Sub;
Sub.prototype.saySub=function(){console.log(this.subPer )}
- es6 class继承
class Super{
constructor(name,super){
this.name=name;
this.superPer = super}
saySuper(){console.log(this.name)}
}
class Sub extends Super{
constructor(name,super,sub){
super(name,super)
this.subPer = sub}
saySub(){console.log(this.subPer )}}
二、原型链
function Fn(){
this.test1=function(){
consolr.log(111)
}
}
Fn.prorotype.test2=function(){
console.log(222)
}
let fn = new Fn()
上述代码的原型链如下图