原型
为什么要用原型
构造函数每次在实例化的过程中,会在内存中将当前函数重新拷贝出来一份,如果实例化很多次,会导致内存中存在很多个一模一样的函数,造成了资源浪费。因此把函数放在原型中
原型是什么
原型是用来存储对象中公共的属性和方法。
每一个对象身上都有原型_ _ proto_ _
每一个函数都有原型prototype:
构造函数.prototype = {}
构造函数.prototype.属性名 = 属性值
构造函数.prototype.方法名 = function(){}
function fn(){}
console.log(typeof fn.prototype);//object
每一个原型身上都有constructor属性,指向当前构造函数
function ani(){
this.name = "猫";
this.age = 1 ;
}
var obj = new ani();
// true
console.log( ani = ani.prototype.construstor)
// true
console.log( ani = ani.__proto__.construstor)
原型链
对象在访问属性或者方法时 会在当前对象找,当前对象没有再到 原型 中找 ,原型找不到 再到 原型里面找,知道找到 object 为止,属性找不到 返回 undifinde 函数报错 is not function
补充:
任何对象都有原型,最底层的object也属于对象,object原型是 null
Object.getPrototypeOf(object.prototype); // null
继承
一个对象拥有了另一个对象的属性和方法
-
原型继承
function Animal(){ eat: function(food){ alert(food) } } function Cat(){ } Cat.prototype = new Animal(); // 将父类(Animal)的实例作为子类(Cat)的原型 var tom = new Cat(); cat.eat('fish') // 弹出 'fish' console.log(tom instanceof Animal); //true console.log(tom instanceof Cat); //true -
对象冒充继承
-
call() 立即执行 ,传递参数用逗号隔开
//继承整个对象 被继承的构造函数.call(谁来继承 的 实例化对象) //继承单个方法,参数使用逗号隔开 被继承的实例化对象.方法.call(谁来继承的实例化对象,arg1,arg2) //arg 参数 -
apply(); 立即执行 ,传递参数用数组[]
//继承整个对象 被继承的构造函数.apply(谁来继承 的 实例化对象) //继承单个方法,参数使用数组 被继承的实例化对象.方法.apply(谁来继承的实例化对象,[arg1,arg2]) //arg 参数 -
blind(): 不立即执行 ,传递参数用逗号隔开
//继承整个对象 被继承的构造函数.blind(谁来继承 的 实例化对象)() //继承单个方法,参数使用逗号隔开 被继承的实例化对象.方法.blind(谁来继承的实例化对象,arg1,arg2)() //arg 参数
-
-
[es6]类继承
new 操作符
- 创建空对象 var obj ={}
- 将空对象的原型指向个构造函数原型
- 将构造函数中的this替换成空对象
this的指向
-
在全局环境中this指
window全局对象 -
作为对象方法调用,this 指代调用该方法对象
-
在构造函数中this指向构造函数的
实例化函数 -
在事件中,this指向事件源
call,apply , bind 修改this指向 this指的是方法中传入的对象,如果apply中没有传对象,this指向window
()里面是谁就指向谁,通常修改this的指向用bind,因为bind不会执行。
var obj = { name : "zhangshan" work:function(){ console.log(this); } . blind($box) } console.log(obj.work());
Object 对象
- Object.assign(obj1,obj2,obj3,......) 合并对象/对象拷贝
- Object.is(a,b);
用于判断两个值是否相同
-
检测fn是否在x对象的原型中
function fn(){ } var x= new fn(); //true console.log(fn.prototype.isPrototypeOf(x)); -
检测对象中是否包含某一属性
var obj = { name :"sss" } console.log(obj.hasOwnProperty("name"))//true console.log(obj.hasOwnProperty("name1"))//false -
数组一字符串的方式输出
var arr = [1,2,3]; console.log(arr.toLocaleString()); // 1,2,3 -
数据检测
-
tyoeof 要检测的变量
-
Object.prototype.toString.call(需要检测的数据 )
//[object Null] Object.prototype.toString.call(nullay //[object Array] var a = Object.prototype.toString.call([]); if( s == "[object Array]") -
instanceof 运算符
var arr =[]; if(arr instanceof Array){ console.log("数组") }
-
-
[ES6]Object.keys(obj)
var obj = { name : " zhangsan", age : 18 } var s = Object.keys(obj); //[name,age] -
[es6]Object.value(obj);
var s = Object.values(obj); //["zhangsan",18]