javascript初体验(一)
数据类型
- 数字 (Number),整数或浮点数,例如42或3.14159
- 字符串 (String)
- 布尔值 (Boolean)
- null (js大小写敏感,因此null和NULL不一样)
- undefined (变量被声明了,但是没有赋值时)
- Symbol (es6中新添加的类型,一种实例是唯一且不可改变的数据类型)
- Object
类型检查
- typeof (可以区别:数值,字符串,布尔值,undefined,function,返回结果是字符串)(不能区别:null和对象,对象和数组)
- instanceof (专门用来判断对象数据类型:Object,Array,function)
- === (undefined,null)
var a;
console.log(a, typeof a, typeof a === "undefined", a === undefined)
//undefined undefined true true
var b = 10;
console.log(typeof b, typeof b === "number")
//number true
var c = true;
console.log(typeof c)
//boolean
var e = "hello"
console.log(typeof e)
//string
var d = null;
console.log(typeof d)
//object
var f = {}
console.log(typeof f)
//object
var g = []
console.log(typeof g)
//object
console.log("---------------------")
var obj = {
obj1: [100, "hello"],
obj2: function () {
}
}
console.log(obj instanceof Object)
//true
console.log(obj.obj1 instanceof Array, obj.obj1 instanceof Object)
//true true
console.log(obj.obj2 instanceof Function, obj.obj2 instanceof Object)
//true true
console.log(obj instanceof Function)
//false
console.log("-----------------------")
console.log(typeof obj)
//object
-
console.log(typeof obj.obj1)
//object
console.log(typeof obj.obj2)
//function
console.log(b instanceof Object)
//false
var h = null
console.log(typeof h, h === null)
//object true
console.log('------------')
严格类型检查 ( == 和 === )
var i = 100;
var j = "100"
console.log(i == j, i === j)
console.log(undefined == null, undefined === null)
console.log(true == 1, true === 1)
引用变量赋值
var obj1={name:"tom"}
function fun (obj){
obj={name:"jack"}
}
fun(obj1)
数据传递
function changeAge(obj){
obj={age:50}
//obj.age=50
}
- 这两种赋值方式不一样,第一种改变了obj的指针指向
函数的调用
function setAge(age){
this.age=age;
}
var p1=new person("tom");
-----------call
这个时候setAge和person是没有关系的
setAge.call(p1,30)
将setAge绑定到p1上,相当于p1.setAge
-----------apply
setAge.apply(p1,[30,20])
************call和apply的区别是call参数是用逗号隔开的,apply是写在数组里
回调函数
常见的回调函数:DOM事件函数、定时器函数、ajax回调函数、生命周期回调函数
IIFE(匿名函数自调用)
- 隐藏内部实现
- 不污染外部命名空间
- 用它来编码js模块·
(function(){
var a=0;
function add(){
return ++a;
}
//将add函数暴露给外界调用
window.$=function(){
return {add:add}
}
})()
函数中的this
当函数被实例化以后,this不再指向window,而是指向实例化对象
function Person(name){
this.name=name;
this.setName=function(name){
this.name=name;
}
this.getName=function(){
return this.name;
}
}
new Person("tom")
- 函数中的this是一个引用变量,哪个实例对象调用的函数,this就指向这个实例
var setName=p1.setName;
setName("rose");
console.log(p1.name)
注意:这里调用setName函数的是window

浙公网安备 33010602011771号