Rumah > Soal Jawab > teks badan
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?
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());
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