进制
类型
数字类型number
布尔类型boolean
字符串类型string
undefined
对象object(null)
function
typeof 可能返回的几个类型
引用值比的是地址;对象跟对象,是两个不同房间,不相等。
this
js中属性名key、 this.key、 window.key:
2.
//
new test()后
4.谁调用它,this就指向谁
题目练习:
解析:
var name = "222"
var a = {
name:"111",
say: function(){console.log("1",this,this.name)}
}
var b = {
name: "333",
say:function(fun){
console.log("2",this,this.name)
fun();
}
}
b.say(a.say)
b.say = a.say;
b.say()
运行结果:
题
var aaa='1';
var obj={
aaa: '2',
A: function(){
this.aaa='4';
console.log(aaa);
}
}
var fun = obj.A;
fun();
obj.A();
解析:
obj.A()先调用是1嘛;this是obj;没有改全局的aaa;输出aaa还是1;后面那个是全局调用 this改了全局的aaa,输出aaa是全局的aaa即4;反过来不一样,是fun先改了全局aaa,所以obj.A()输出都是4了。
new
new的作用
1、创建一个新的对象
2、将构造函数的this指向这个新对象
3、返回这个新对象
一个对象中没有的属性打印出来是 undefined
扩散题:
()先把bar.a从002变成了a,b也赋值了,并且 返回了函数;
然后再()执行输出: a b
this指向补充
- 全局环境当中this指向全局对象
- 函数中的this,由调用函数的方式来决定
a、如果函数是独立调用,在严格模式下是禁止this指向全局对象,而是指向undefined。在非严格模式下,this会指向window
b、如果函数是被某一个对象调用,那this指向被调用的这个对象 - 构造函数与原型里的this
a、构造函数里的this以及原型里的this对象指向的都是生成的实例,原因就是由new决定的
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
/*
this指向
1、全局环境当中this指向全局对象
2、函数中的this,由调用函数的方式来决定
1、如果函数是独立调用,在严格模式下是禁止this指向全局对象,而是指向undefined。在非严格模式下,this会指向window
2、如果函数是被某一个对象调用,那this指向被调用的这个对象
3、构造函数与原型里的this
1、构造函数里的this以及原型里的this对象指向的都是生成的实例,原因就是由new决定的
*/
//var this=12;
/* console.log(this==window); //Window
var obj={a:10};
function fn(){
'use strict'
console.log(this);
}
fn(); //undefined
fn.call(obj); //obj */
/* var obj={
a:20,
b:this.a+20,
fn:function(){
console.log(this);
return this.a;
}
}
console.log(obj.b); //NaN
console.log(obj.fn()); //20 */
/* var a=20;
var obj={
a:10,
getA:function(){
return this.a;
}
}
console.log(obj.getA()); //10
var test=obj.getA;
console.log(test()); //20 */
var a=13;
function fn1(){
var a=9;
console.log(this.a); //13
}
function fn2(fn){
var a=5;
fn();
//fn.call(fn2)
}
var obj={
a:10,
getA:fn1
}
fn2(obj.getA);
//fn.call(fn2)
/* function fn(){
'use strict';
var a=1;
var obj={
a:10,
c:this.a+20
}
return obj.c;
} */
//console.log(undefined.a)
//console.log(fn());
//var abc=12;
//console.log(abc); //用一个不存在的变量会报错
//console.log(window.abc); //用一个不存在的属性,结果为undefined
/* function Person(name,age){
this.name=name;
this.age=age;
console.log(this);
}
Person.prototype.getName=function(){
//this
console.log(this);
};
var p1=new Person('kaivon',18);
p1.getName(); //kaivon */
/*
new的作用
1、创建一个新的对象
2、将构造函数的this指向这个新对象
3、返回这个新对象
*/
</script>
</body>
</html>