基本类型函数
String ,null,undefined,number,boolean性能
引用类型:
objectthis
原型:spa
function People(name,sex){ this.name=name; this.sex=sex; }
people构造函数上有属性prototype,prototype为原型对象;prototype
var p1=new People('canoe','girl');code
p1为People实例对象,每一个对象上都有__proto__,而__proto__指向的是原型对象,而原型对象上有__proto__属性,指向的是上一级的原型对象。就这么依次向上查找,直到null对象
各类继承,优缺点:继承
1.原型链继承ip
// 定义一个动物类 function Animal (name) { // 属性 this.name = name || 'Animal'; // 实例方法 this.sleep = function(){ console.log(this.name + '正在睡觉!'); } } // 原型方法 Animal.prototype.eat = function(food) { console.log(this.name + '正在吃:' + food); };
核心: 将父类的实例做为子类的原型原型链
function Cat(){ } Cat.prototype = new Animal(); Cat.prototype.name = 'cat'; // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.eat('fish')); console.log(cat.sleep()); console.log(cat instanceof Animal); //true console.log(cat instanceof Cat); //true
优势:
缺点:
2.构造继承
核心:使用父类的构造函数来加强子类实例,等因而复制父类的实例属性给子类(没用到原型)
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // false console.log(cat instanceof Cat); // true
优势:
缺点:
三、实例继承
function Cat(name){ var instance=new Animal(); instance.name=name||"tom"; return instance } // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); // false
优势:
缺点:
四、组合继承
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } Cat.prototype = new Animal(); Cat.prototype.constructor=Cat; // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); // true
优势:
缺点:
五、寄生组合继承
核心:经过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点
function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){ // 建立一个没有实例方法的类 var Super = function(){}; Super.prototype = Animal.prototype; //将实例做为子类的原型 Cat.prototype = new Super(); })(); // Test Code var cat = new Cat(); console.log(cat.name); console.log(cat.sleep()); console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); //true