提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
目录
1.this
this代表离它最近的嵌套级别的function的调用者,如果没有就是window
console.log(this) ==> window
obj.xx()==>obj
x.x.x[1]()==>x.x.x
fn().x()==>fn()的返回值
2.new
new后面一般跟一个函数 new会创建对象,而且会去调用这个函数
new fn===>创建对象 然后调用函数 不传参==>new无参
new fn()==>创建对象 然后调用函数 并传参数==>new带参
程序举例1:
function fn(a) {
this.a = a
this.b = 20
//这是一个函数的代码块,想写什么就写什么
for (var i = 0; i < 10; i++) {
console.log(i)
}
return "hello";
}
var re = new fn
console.log(re)
运行结果:
程序举例2:
function fn(a) {
this.a = a
this.b = 20
//这是一个函数的代码块,想写什么就写什么
for (var i = 0; i < 10; i++) {
console.log(i)
}
return "hello";
}
var re2 = new fn(200)
console.log(re2)
运行结果:
程序举例3:
function fn(a) {
this.a = a
this.b = 20
//这是一个函数的代码块,想写什么就写什么
for (var i = 0; i < 10; i++) {
console.log(i)
}
return "hello";
}
var re2 = new fn(200)
console.log(re2)
运行结果:
js是一个基于面向对象的单线程的脚本语言
程序举例4:
function fn() {
this.name = "karen"
return function fm() {
console.log("fm运行了")
this.name = "jack"
}
}
var f1=new fn()
console.log(f1.name)//"fm"
注释:
f1
1.{}
2.{}.fn()里面的this是这个空对象==> {name:"Karen"}
3.f1=为fn函数返回值是不是引用数据 是就是它 不是就是那个创建的对象
运行结果:
程序举例5:
function fn() {
this.name = "karen"
return function fm() {
console.log("fm运行了")
this.name = "jack"
}
}
var f1=new fn()
var f2=new (new fn())()
console.log(name)//window.name ==> ""
console.log(f2.name)
注释:
console.log(x)//报错
console.log(window.x)//undefined 后面原型链讲
运行结果:
3.this-new-构造函数
(1)程序例题
程序举例1:
function fn() {
this.name="marry"
var obj = {
name:"karen",
fm: function() {
this.name="jack"
}
}
return obj;
}
var f1=new fn() //{name:"marry"} f1=obj=>{name:"karen",fm:}
console.log(f1.name) //karen
var f2=new ((new fn()).fm) ()
console.log(f2.name) //jack
运行结果:
(2)程序例题
程序举例2:
function fn() {
this.name="marry"
var obj = {
name:"karen",
fm: function() {
this.name="jack"
}
}
return obj;
}
var f3=new fn()
var f4=new (f3.fm) () //{name:"jack"}
console.log(f3.name,f4.name) //karen,jack
运行结果:
4.this-new-构造函数程序分析
(1)程序:this.a=1,this.b=[1,2,this.a],this.c={demo:5};
function Parent() {
this.a = 1;
this.b = [1, 2, this.a];
this.c = {
demo: 5
};
this.show = function() {
console.log(this.a, this.b, this.c.demo);
}
this.change = function() {
this.a = this.b.length;
this.c.demo = this.a++;
}
return {
show:function(){console.log(1,2,3)},
change:function(){console.log(1,2,3)}
}
}
var parent = new Parent();
parent.change();
parent.show();
注释:
var parent = new Parent();
==> var parent={a:4,b:[1,2,1],c:{demo:3},show:func,change:func}
parent.show(); ==> 4 [1,2,1] 3
运行结果: