函数定义如下;
function showmsg()
{
console.log(this);
}
首先函数大致有三种调用方式
1 直接调用的话 默认this是全局对象Window
showmsg();
//Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}
2 如果把一个函数绑定到某个对象上去 那么this就是那个对象了
var obj = {a: 1, b: 2, showmsg: showmsg};
obj.showmsg();
//Object {a: 1, b: 2, showmsg: function}
3 还有一种方式作为构造器使用
根据第二条的结论 User当中的this就是showmsg当中的this
那么User当中的this是什么呢?
function User(name, age)
{
this.name = name;
this.age = age;
this.showmsg = showmsg;
}
var u = new User("wiz", 21);
u.showmsg();
//User {name: "wiz", age: 21, showmsg: function}
由此看来this还是个对象 只不过constructor变成了User
构造器当中的this实际上是new了一个Object 然后把constructor变成了这个函数
=============================
看你问题改了 补充一下吧
obj.a(); //静态调用
var a = "...";
obj[a](); //动态调用
(function(...){...})(this);
定义一个函数对象后马上调用它 这样不需要给函数一个名字
括号的作用是把语句转化为表达式
this
的指向大致有四种:
1.函数调用
的时候,this指向window
。
function aa(){
console.log(this)
}
aa() //window
2.当是方法调用
的时候,this指向方法所在的对象
。
var a={}
a.name = 'hello';
a.getName = function(){
console.log(this.name)
}
a.getName() //'hello'
3.构造函数
模式的时候,this指向新生成的实例
。
function Aaa(name){
this.name= name;
this.getName=function(){
console.log(this.name)
}
}
var a = new Aaa('kitty');
a.getName() // 'kitty'
var b = new Aaa('bobo');
b.getName() // 'bobo'
4,apply/call
的时候,this指向`apply/call方法中的第一个参数。
var list1 = {name:'andy'}
var list2 = {name:'peter'}
function d(){
console.log(this.name)
}
d.call(list1) // 'andy'
d.call(list2) // 'peter'
题主,你是不理解which this val
么?
如果是,我这里描述一下。
this
指向的是function
的调用对象 //大概这么理解
所以 里面那个this
,就表示User {}
;
(function(w){
//调用w
w;
})(a);//实际上w就相当于a了
对应你这个例子,效果就是使得 你后面 user.getname
是一个function
而那个val
,例子没点出来用法,就是user.setname("我是技术宅")
想想function
函数表达式和定义表达式。