function User( properties ){
for( var i in properties ){
(function( which ){
var p = i;
which[ "get" + i ] = function(){
return properties[p];
};
which[ "set" + i ] = function(val){
properties[p] = val;
}
})(this);
}
}
var user = new User({
name : "Bob",
age : 44
});
console.log(user.name);
console.log(user.getname());
console.log(user.getage());
这是JS面向对象编程书上的一个例子,我想问问这个实际有用处吗? 虽然我对闭包什么的略知一点可是这里的 which this val 搞的我好晕 求牛人解释一下。。。
再问一个
Function.prototype.method = function(name, func){
this.prototype[name] = func;
return this;
};
所以name必须是个string? this.prototype[name]中的this 和 return this 分别指的是?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
题主,你是不理解
which this val么?如果是,我这里描述一下。
this指向的是function的调用对象 //大概这么理解所以 里面那个
this,就表示User {};对应你这个例子,效果就是使得 你后面
user.getname是一个function而那个
val,例子没点出来用法,就是user.setname("我是技术宅")想想
function函数表达式和定义表达式。this的指向大致有四种:1.
函数调用的时候,this指向window。2.当是
方法调用的时候,this指向方法所在的对象。3.
构造函数模式的时候,this指向新生成的实例。4,
apply/call的时候,this指向`apply/call方法中的第一个参数。函数定义如下;
首先函数大致有三种调用方式
1 直接调用的话 默认this是全局对象Window
2 如果把一个函数绑定到某个对象上去 那么this就是那个对象了
3 还有一种方式作为构造器使用
根据第二条的结论 User当中的this就是showmsg当中的this
那么User当中的this是什么呢?
由此看来this还是个对象 只不过constructor变成了User
构造器当中的this实际上是new了一个Object 然后把constructor变成了这个函数
=============================
看你问题改了 补充一下吧
定义一个函数对象后马上调用它 这样不需要给函数一个名字
括号的作用是把语句转化为表达式