首页 > JAVASCRIPT OOP 闭包 this指代 动态get,set

JAVASCRIPT OOP 闭包 this指代 动态get,set

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 分别指的是?


题主,你是不理解which this val么?
如果是,我这里描述一下。


this指向的是function的调用对象 //大概这么理解

所以 里面那个this,就表示User {};

(function(w){
  //调用w
  w;
})(a);//实际上w就相当于a了

对应你这个例子,效果就是使得 你后面 user.getname是一个function

而那个val,例子没点出来用法,就是user.setname("我是技术宅")
想想function函数表达式和定义表达式。


函数定义如下;

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' 
【热门文章】
【热门文章】