search

Home  >  Q&A  >  body text

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?

PHP中文网PHP中文网2896 days ago451

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-10 14:35:56

    Person.methods.say.call(Person)

    reply
    0
  • PHPz

    PHPz2017-04-10 14:35:56

    貌似你这种写法只能使用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());
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:35:56

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

    给你一个参考的例子:

    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

    reply
    0
  • Cancelreply