从另一个属性引用js属性的正确方式

Proper way to reference js property from another property

本文关键字:属性 方式 js 另一个 引用      更新时间:2023-09-26

我正在进行一个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