从另一个属性引用js属性的正确方式
Proper way to reference js property from another property
我正在进行一个angular项目,我有一个工厂提供一些全局数据库方法。我在jsfiddle中测试了这一点,它确实有效,但我想知道这是否是正确的方法
这是jsFiddle。
function DB () {
return {
newRecord: function () {
//create new record
var id = 3;
//this is the part I am wondering about
//is it ok to use this in this way??
this.setCurrentRecordId(id);
},
setCurrentRecordId: function (id) {
alert('setting id');
return localStorage.setItem('id', id);
},
getCurrentRecordId: function () {
return localStorage.getItem('id');
}
}
}
var dbStuff = new DB();
dbStuff.newRecord();
alert(dbStuff.getCurrentRecordId());
正如我所说,它似乎正在发挥作用;只是想知道是否有更好的方法。
谢谢!
在JavaScript中使用构造函数的"标准"方式如下:
function DB () {
this.newRecord = function () {
var id = 3;
// yes, since you invoked the DB constructor using
// using the new keyword, this will be pointing to
// the created instance
this.setCurrentRecordId(id);
};
this.setCurrentRecordId = function (id) {
alert('setting id');
return localStorage.setItem('id', id);
};
this.getCurrentRecordId = function () {
return localStorage.getItem('id');
};
}
var dbStuff = new DB();
dbStuff.newRecord();
alert(dbStuff.getCurrentRecordId());
如果您需要在回调中引用实例,或者在其他上下文丢失的情况下,有两种常见的模式可以处理此问题。
要么存储对此的引用(有些人认为这是"丑陋的",但非常方便):
function Ctor(){
var self = this;
this.getSomething = function(id){
asyncThing(id).then(function(result){
// here, `this` will refer to the global object
self.doSomethingWith(result);
});
};
this.doSomethingWith = function(result){
// do something
};
}
或者使用.bind()
创建一个具有预定义上下文的新函数:
function Ctor(){
this.getSomething = function(id){
var processResult = function(arg){
this.doSomethingWith(arg);
}.bind(this); // bind sets the function's context no matter where you'll use it
asyncThing(id).then(processResult);
};
this.doSomethingWith = function(result){
// do something
};
}
由于您使用的是本地存储,因此没有任何问题。
function DB () {
return {
setCurrentRecordId: function (id) {
alert('setting id');
return localStorage.setItem('id', id);
},
getCurrentRecordId: function () {
return localStorage.getItem('id');
}
}
}
var dbstuff = new DB();
dbstuff.setCurrentRecordId(3);
dbstuff.getCurrentRecordId() // 3
相关文章:
- 为Google闭包类定义属性的首选方式是什么
- 向插件添加属性(不是默认方式)
- 使用 onChange 属性以内联方式更改复选框的值
- 为什么某些Javascript属性没有在调试器中以交互方式显示
- 在Javascript构造函数中定义属性的正确方式
- 如何生成一个正则表达式,用以这种方式命名的类的属性值替换标记{{name}}
- 以编程方式为传单地图上的标记提供数据属性
- BackboneJS重新排列集合中模型的最佳方式,同时为每个模型维护0索引的有序属性
- 复制元素的最佳方式是:只复制元素的类型和属性
- 如何以编程方式获取属性Id、视图Id和帐户Id
- 如何以编程方式展开/折叠属性
- 使用方法和属性定义javascript对象的最佳方法是什么?(如果可能以本机方式)
- 下划线/洛达什号中的快捷方式,用于(递归)设置对象的所有属性
- 两个 JavaScript 对象具有相同的属性实现方式,但原型不同
- JavaScript 中通过公共属性“交叉”两个 JSON 对象数组的最佳方式
- Drupal 7 Field API:如何以编程方式发送表单元素属性 #ajax 指定的AJAX请求
- 无法设置未定义的 - 以编程方式创建的元素的属性 X
- 在循环或以其他方式动态创建 JSON 对象中的属性
- 更改属性 Javascript 方式的值
- 我怎么能加载数组的i18n字符串在javascript的属性方式