关于 JavaScript 原型和继承的思考

闭包和原型

prototype

  • 工厂函数
function user(name){
    var newUser = {};
    newUser.name = name;
    return newUser;
}
复制代码
  • 构造函数
//使用new的是 构造函数
function User(name,age,gender){
    this.name = name ; 
    this.age = age ;
    this.gender = gender ;
}

var whh = new User('whh',16,'male');
//生成对象的过程叫做实例化
console.log('whh:',whh)
复制代码
  • 理解 prototype 和 _proto_
function User(name,age,gender){
    this.name = name ; 
    this.age = age ;
    this.gender = gender ;
    this.eat = function(){
      console.log('miao')  
    } ;
    this.greeting = function(){
        console.log('yo! my name is '+this.name)
    }
}

//每次需要实例化,每个新的new 都是不同的浪费空间

复制代码
  • 使用prototype 方法
function A(){}

A.prototype.name = 'lala';

var a = new A();
var b = new A();

console.log(a._proto_ **= b._proto_)
// true

//a.constructor() **= A(){}
复制代码

原生对象的原型

var aa = {};
var bb = new Object();
console.log(a.constructor **= b.constructor)//true

//纯洁的 object
var pure = Object.create({
    
});
console.log('pure:',pure)

//测试数组
var a = [];
var a = new Array();
console.log('a',a)
复制代码

多级继承链怎么实现

function Animal(color,weight){
    this.color = color;
    this.weight = weight;
    // this.eat = function(){
    //     console.log('mia mia mia...');
    // }

    // this.sleep = function(){
    //     console.log('hu lu lu...');
    // }
}

Animal.prototype.eat = function(){
    console.log('mia mia mia...');
}

Animal.prototype.sleep = function(){
    console.log('hu lu lu...');
}

function Manmal(color,weight){
    //绑定Animal的 显性属性的继承方式 
    Animal.call(this,color,weight);
}

function Person(color,weight) {
    //绑定Animal的 本地属性 
    Manmal.call(this,color,weight);
}

//继承能力
var a = new Animal();
var b = new Animal();

console.log('a.eat **= b.eat:',a.eat **= b.eat);
var lsd = new Person();

//使用继承 manmal --> animal
Manmal.prototype = Object.create(Animal.prototype); 
Manmal.prototype.constructor =  Manmal;
//将继承的constructor 再重新指回 Manmal constructor应该为父辈,这里指向了爷爷
Manmal.prototype.suckle = function(){
    console.log('biu biu biu...');
}

var m =new Manmal('red',80);
console.log('m:',m);
// m.__proto__ // --> Object Animal
// m.constructor //  -->func Animal
//改进以后 Manmal 为 m 的生产厂家

//修改Person
Person.prototype = Object.create(Manmal.prototype);
Person.prototype.constructor = Manmal;
Person.prototype.lie = function(){
    console.log('你不帅!');
}

var lsd = new Person('hei',12);
console.log('lsd:',lsd);
复制代码

总结

几个原型链之间的关系:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值