Skip to content
Neuron Teckid edited this page Dec 29, 2015 · 2 revisions

在 Flatscript 中, this 对象的概念与 Javascript 中基本一样, 只是表示方式不同. 下文中的 this 均指代 Javascript 中的 this 对象的概念. this 在 Flatscript 中并不是一个保留字.

在一个函数中出现的 this 对象的引用将与其在 Javascript 函数中对应的对象引用一致 (以成员函数形式调用函数时的对象引用, 或以普通函数调用时对全局对象的引用).

this 属性引用

使用 this 关键字后连用点号 (.) 及标识符表示对 this 对象属性的引用. 如

this.prop
this.function

这些将被转换成与下面 Javascript 表达式对应等价的表达式

this["prop"]
this['function']

this 引用范围

在一个域级函数的函数体或 lambda 函数体中, this 所表示的对象一定是同一个对象, 无论该函数体是否受到异步占位符的影响. 如

func handleMove(evt)
    this.handleMove: (): null
    moveElement(this, evt)
    setTimeout(%, 20)
    this.handleMove: handleMove

将被转换成与下面 Javascript 函数定义对应等价的函数定义

function handleMove(evt) {
    var this_ = this;
    this_.handleMove = function() { return null; };
    moveElement(this_, evt);
    setTimeout(function() {
        this_.handleMove = handleMove;
    }, 20)
}

或如

func changeColor(colorList)
    colorList |:
        this.style.backgroundColor: $
        setTimeout(%, 2000)
    console.log('Done')

将被转换成与下面 Javascript 函数定义对应等价的函数定义

function changeColor(colorList) {
    var this_ = this;
    function next_(index, result) {
        if (index === result.length) {
            console.log('Done');
        } else {
            (function() {
                this_.style.backgroundColor = colorList[index];
                setTimeout(function() {
                    next_(index + 1, result);
                }, 2000);
            })(index, colorList[index]);
        }
    }
    next_(0, []);
}

如果有嵌套的函数定义 (包括域级函数定义与多行 lambda 的互相嵌套), 那么内层函数中所引用的 this 对象将与外层函数引用的 this 对象不同.

this 不能在全局空间中被使用.