继承模式
- 传统模式 -->原型链(过多的继承了没用的属性)
Grand.prototype.lastName = 'wu'
function Grand() {}
var grand = new Grand()
Father.prototype = grand
function Father(){
this.name = 'hehe'
}
var father = new Father()
Son.prototype = father
function Son() {}
var son = new Son()
console.log(son.lastName) //wu 他会继承这个属性
- 使用构造函数(1.不能继承借用构造函数的原型2.每次构造函数都要多走一个函数)
function Person(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
function Student(name,age,sex,grade,tel){
Person.call(this,name,age,sex)
this.grade = grade
this.tel = tel
}
var student = new Student()
console.log(student.constructor) //student(){} 而且还要走person这个函数
- 共享原型(不能随便改动自身的原型)
Father.prototype.lastName = 'wu'
function Father(){}
function Son(){}
Son.prototype = Father.prototype
var son = new Son()
console.log(son.lastName) //wu
son.prototype.lastName = 'zhang'
console.log(Father.prototype.lastName) //zhang
- 圣杯模式
function(target, origin){
function F() {}
F.prototype = origin.prototype
//var f = new F()
target.prototype = new F()
target.prototype.constructor = target
}
完美圣杯模式
var inherit = (function(){
var F = function(){}
return function(target, origin){
F.prototype = origin.prototype
target.prototype = new F()
target.prototype.constructor = target
target.prototype.under = origin.prototype
}
}())
命名空间
- 作用:管理变量,防止污染全局,适用于模块开发
var init = (function (){
var name = 'abc'
function callName(){
console.log(name)
}
return function(){
callName();
}
}())
如何做到jquery中的链式调用方法
var wu = {
smoke:function(){
console.log('smoking is cool')
return this
}
drink:function(){
console.log('drinking is cooling')
return this
}
perm:function(){
console.log('perm is cool')
return this
}
}
wu.smoke().drink().perm()//smoking is cool drinking is cooling perm is cool 如果不返回this它会默认返回undefined
js中取对象属性时’.‘和’[]'的区别
var obj = {
name: ' abc'
}
obj.name -->obj['name']
对象的枚举
- for in用于遍历对象的key
var obj = {
name : 'wu',
age : 18,
sex : 'male',
height : 180,
weight : 75
}
for(var prop in obj){
console.log(obj[prop])//obj.prop 打印不出来
}
- hasOwnerProperty()用来区分自己的属性还是原型上的属性
var obj = {
name : 'wu',
age : 18,
sex : 'male',
height : 180,
weight : 75,
__proto__:{
lastName: 'zhang'
}
}
for(var prop in obj){
console.log(obj[prop])//wu 18 male 180 75 zhang
}
for(var prop in obj){
if(obj.hasOwnerProperty(prop)){
console.log(obj[prop]
} // wu 18 male 180 75
- in 用于区分属性是不是属于自己
var obj = {
name : 'wu'
}
console.log( 'name' in obj) //true
- instanceof 查看自己的原型链上是不是有某个构造函数
//A 对象 是不是 B构造函数构造出来的
//看A对象的原型链上 有没有 B的原型
A instanceof B
区分数组和对象的三种方法
var obj = {}
var arr = []
typeof obj //object
typeof arr //object
//利用constructor
obj.constructor //function Object(){}
arr.constructor //function Array(){}
//利用instanceof
obj instanceof Array//false
arr instanceof Array //true
//Object.prototype.toString.call
Object.prototype.toString.call(arr)//[object Array]
Object.prototype.toString.call(obj)//[object Object]