【问题标题】:how would one not use `this` in a JavaScript object {}?怎么会不在 JavaScript 对象 {} 中使用 `this`?
【发布时间】:2014-08-26 21:05:54
【问题描述】:

在Norway this yearDoug Crawford 宣布他不再在 JavaScript 中使用this(或者他的意思是 ES6?)。真诚的,这里怎么不使用this:

var indexViewModel = {

    currentIndex: ko.observable(0),
    currentPage: ko.observable(1),
    displayItems: ko.observableArray(),

    indexSegmentsForPeople: [
        { id: "poetryinxhtml", text: "Poetry in XHTML5" },
        { id: "poetryinpdf", text: "Poetry in PDF" },
        { id: "poetryinstreams", text: "Poetry in Streams" },
        { id: "digitizedart", text: "Digitized Art" }
    ],
    indexSegmentsForTime: [
        { id: "prose", text: "Prose" },
        { id: "interviewsanddocumentary", text: "Interviews/Documentary" },
        { id: "therasxcontext", text: "the rasx() context" }
    ],
    indexVisitorLinks: [
        { url: "./rasx01.html", title: "about the kinté space" },
        { url: "./kfaqs.html", title: "kinté FAQs" },
        { url: "./khits.html", title: "kinté hits" },
        { url: "./rasx00.html", title: "the kinté space oddity" }
    ],
    items: [],
    itemsCount: ko.observable(0),
    itemsPerPage: 9,
    pageCount: ko.observable(0),

    getCurrentIndex: function () {
        return ((this.currentPage() - 1) * this.itemsPerPage);
    },
    getJSON: function (id) {
        var url = this.getIndexJsonUrl(id);
        var that = this;
        return $.getJSON(url).then(function (data) {
            that.setItems(data);
        });
    },
    getJSONforVisitors: function () {
        var that = this;
        return $.getJSON('./data/VisitorThumbs.json').then(function (data) {
            that.setItemsForVisitors(data);
        });
    },
    getIndexJsonUrl: function (id) {
        return './data/index-' + id + '.json';
    },
    getIsNewValue: function (pubDate) {
        var now = new Date();
        var test1 = ((now.getMonth() - pubDate.getMonth()) <= 2);
        var test2 = (pubDate.getFullYear() === now.getFullYear());
        return (test1 && test2);
    },
    getSlice: function () {
        return this.items.slice(this.currentIndex(),
                (this.currentIndex() + this.itemsPerPage));
    },
    isNextPageEnabled: ko.observable(true),
    isPreviousPageEnabled: ko.observable(false),
    setDisplayItems: function () {
        var that = this;
        var slice = this.getSlice();
        this.displayItems.remove(function (item) { return item; });
        _(slice).each(function (item) { that.displayItems.push(item); });
    },
    setEnabled: function () {
        this.isNextPageEnabled(this.currentPage() < this.pageCount());
        this.isPreviousPageEnabled(this.currentPage() > 1);
    },
    setItems: function (data) {
        var that = this;
        this.items = _(data.ChildDocuments)
            .sortBy(function (d) { return $.rx.dateTime.getJsonDate(d.CreateDate); }).reverse();

        _(this.items).each(function (item) {
            //Add .isNew property:
            var pubDate = $.rx.dateTime.getJsonDate(item.CreateDate);
            item.isNew = that.getIsNewValue(pubDate);
        });

        this.currentIndex(0);
        this.currentPage(1);
        this.itemsCount(this.items.length);
        this.pageCount(Math.ceil(this.itemsCount() / this.itemsPerPage));
        this.setDisplayItems();
        this.setEnabled();
    },
    setItemsForVisitors: function (data) {
        this.items = data.ChildDocuments;

        this.currentIndex(0);
        this.currentPage(1);
        this.itemsCount(this.items.length);
        this.pageCount(Math.ceil(this.itemsCount() / this.itemsPerPage));
        this.setDisplayItems();
        this.setEnabled();
    },
    setNextPage: function () {
        this.currentPage(this.currentPage() + 1);
        this.setEnabled();
        if (this.currentPage() > this.pageCount()) { this.currentPage(this.pageCount()); }
        this.currentIndex(this.getCurrentIndex());
        this.setDisplayItems();
    },
    setNextPageClickGate: function () {
        if (this.isNextPageEnabled()) { this.setNextPage(); } else { return false; }
    },
    setPreviousPage: function () {
        this.currentPage(this.currentPage() - 1);
        this.setEnabled();
        if (this.currentPage() < 1) { this.currentPage(1); }
        this.currentIndex(this.getCurrentIndex());
        this.setDisplayItems();
    },
    setPreviousPageClickGate: function () {
        if (this.isPreviousPageEnabled()) { this.setPreviousPage(); } else { return false; }
    },
    triggerAfterAdd: function (item, iterator) {
        $(window.document).trigger('afterAdd',
            ['IndexFlowTemplate', item, iterator]);
    }
};

???

【问题讨论】:

  • 不确定他的意思,但你可以在任何你使用this的地方使用indexViewModel。
  • 也许他的意思是他不使用原型继承。我不确定很多人是否愿意观看一个小时长的视频,只是为了抓住他发表该声明的要点,因此如果您注意视频中的相关时间戳,将会有很大帮助。
  • 克罗克福德说了很多我觉得很傻的话。
  • 我同意饼干怪物。我以前说过,我再说一遍:Crockford 确实推动了有关 JavaScript 的讨论,但并不是所有从他嘴里说出来的东西都是金子。
  • 我也同意 - Crockford 有很多非常有效的观点,但有时似乎将他的个人风格与绝对正确性混淆了。一个很好的例子是他从不希望您使用 ++,因为较少的程序员可能不理解运算符。愤世嫉俗和愚蠢。

标签: javascript ecmascript-6


【解决方案1】:

你的 sn-p 在我看来并不特别地道。这很像将 Java 代码直接翻译成 Javascript。在 JS 中,通常的“代码单元”(代码+数据)是一个闭包,而不是一个对象:

var indexViewModel = (function() {

    var
        currentIndex = ko.observable(0),
        currentPage = ko.observable(1),
        etc...

    function getCurrentIndex() {
        return (currentPage() - 1) * itemsPerPage;
    };

    function getJSON(id) {
        var url = getIndexJsonUrl(id);
        return $.getJSON(url).then(function (data) {
            setItems(data);
        });
    };

    etc....

    return {
        // whatever needs to be public
    };

})();

基本上,所有“对象成员”都变成了局部变量,而“私有方法”=局部函数。如您所见,根本不需要this(更不用说that=this)了。代码更加简洁明了。

【讨论】:

  • 我有 JavaScript the Good Parts 并且会寻找类似“在 JS 中通常的“代码单元”(代码+数据)是一个闭包,而不是对象”,因为这是非常非常重要的,我似乎错过了这个......
  • @rasx:为清楚起见,我并没有引用 Crockford 的话,这是我自己的观点。
【解决方案2】:

不确定你在问什么? Crockford 不会编写类似的代码。他的代码根本不使用this。这是一个设计问题——我的意思是,当然,你可以使用以传统的面向对象风格编写的代码并删除this's,但你会得到一团糟。你必须重新设计整个东西。

Crockford 只是将所有方法调用视为函数调用;没有接收者,只有传入的参数。对象被视为散列,它们的属性只能从外部访问。如果一些代码需要引用私有值,它会使用局部变量的闭包。

不,它与 ES6 无关。除了隐式对象属性初始化等一些小便利之外,ES6 似乎唯一改变了他的编码方式,就是他将使用尾递归来消除循环。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    相关资源
    最近更新 更多