一、检测数据类型
- A instanceof B
- Object.prototype.toString.call(需要检测的数据)
1、typeof
typeof 需要检测的数据
typeof 'sss'
2、constructor
- 检测原理:通过原型上的constructor的指向为函数本身来确定函数类型
function isArray(a){
return a.constructor ===Array
}
isArray([])
isArray({})
3、instanceof
- 用法:A instanceof B (B一般为数据类型)
- 原理:从A到基类的原型,在这条原型链上没有B的原型的存在;
特殊:只能适用于引用数据类型,值类型不适用
let ary = []
var num = 1;
console.log(num instanceof Number);
console.log(ary instanceof Number );
console.log(ary instanceof Array );
console.log(ary instanceof Object );
4、手写push、forEach、map
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
function Person(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.eat = function () {};
let p1 = new Person('张三', 1);
console.log(p1);
console.log(Object.keys(p1));
Object.keys(p1).forEach((k) => {
console.log(k);
})
Object.prototype.hasPubProperty = function (key) {
return (key in this) && !this.hasOwnProperty(key)
}
p1.hasPubProperty('eat')
p1.hasOwnProperty('name')
var ary = [1,2,4]
Array.prototype.myMap = function(cb){
let array = [];
array.length = this.length;
for(var i = 0;i<this.length;i++){
array[i]=cb(this[i])
}
return array
}
ary.myMap(item=>{
return
})
</script>
</body>
</html>
习题
var num=10
var obj={num:20}
obj.fn=(function(num){
this.num=num*3
num++
return function(n){
this.num+=n
num++
console.log(num)
}
})(obj.num)
var fn=obj.fn
fn(5)
obj.fn(10)
console.log(num,obj.num)
function Fn(){
this.x=100
this.y=200
this.getX=function(){
console.log(this.x)
}
}
Fn.prototype.getX=function(){
console.log(this.x)
}
Fn.prototype.getY=function(){
console.log(this.y)
}
var f1=new Fn
var f2=new Fn
console.log(f1.getX==f2.getX)
console.log(f1.getY==f2.getY)
console.log(f1.__proto__.getY==Fn.prototype.getY)
console.log(f1.__proto__.getX==f2.getX)
console.log(f1.getX===Fn.prototype.getX)
console.log(f1.constructor)
console.log(Fn.prototype.__proto__.constructor)
f1.getX()
f1.__proto__.getX()
f2.getY()
Fn.prototype.getY()
var fullName="languge"
var obj={
fullName:'javascript',
prop:{
getFullName:function(){
return this.fullName
}
}
}
console.log(obj.prop.getFullName())
var test=obj.prop.getFullName
console.log(test())
var name="window";
var Tom={
name:"Tom",
show:function(){
console.log(this.name);
},
wait:function(){
var fun=this.show;
fun();
}
};
Tom.wait();
function fun(){
this.a=0;
this.b=function(){
alert(this.a);
}
}
fun.prototype={
b:function(){
this.a=20;
alert(this.a);
},
c:function(){
this.a=30;
alert(this.a)
}
};
var my_fun=new fun();
my_fun.b();
var n=2
var obj={
n:3,
fn:(function(n){
n+=2
this.n+=2
var n=5
return function (m){
this.n*=2
console.log(m+(++n))
}
})(n)
}
var fn=obj.fn
fn(3)
obj.fn(3)
console.log(n,obj.n)