javascript中的this获取不到

var person = function(name){
    this.name = name;
}

person.prototype = {
    empty: function(value){
        return !!value;
    },
    isName: function(){
        return this.empty(this.name);
    },
    methods: {
        say: function(){
            return 'My name is ' + this.name;
        }
    }
};


var Person = new person('Sanonz');
alert(Person.methods.isName());
//执行这个报错,怎么才能在say方法中访问this.name?

怎么才能在say方法中访问this.name?

阅读 6k
3 个回答

Person.methods.say.call(Person)

貌似你这种写法只能使用call或apply来注入了,可以先了解一下js的作用域问题。
或者改变一下接口,如:

var person = function(name){
    this.name = name;
}

person.prototype = {
    empty: function(value){
        return !!value;
    },
    isName: function(){
        return this.empty(this.name);
    },
    say: function(){
        return 'My name is ' + this.name;
    }
};


var Person = new person('Sanonz');
alert(Person.say());

可能你对这种模式存在误用。

给你一个参考的例子:

var RestClient = function () {
    this.methods={};

    this.registerMethod = function(name, url, method){
        // create method in method registry with preconfigured REST invocation
        // method
        this.methods[name] = new Method(url,method);
    };

    this.unregisterMethod = function(name){
        delete this.methods[name];
    };
}

// 使用
var client = new RestClient();

// direct way
client.get("http://remote.site/rest/xml/method", function(data, response){
            // parsed response body as js object
            console.log(data);
            // raw response
            console.log(response);
        });

// 注册 remote methods
client.registerMethod("jsonMethod", "http://remote.site/rest/json/method", "GET");

client.methods.jsonMethod(function(data,response){
    // parsed response body as js object
    console.log(data);
    // raw response
    console.log(response);
});

https://www.npmjs.org/package/node-rest-client

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题