关于function里的this问题

我是js新人,这是knockout.js里的一個示例

html

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>

Js

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
    
    this.fullName = ko.computed(function(){
        return this.firstName() + " " + this.lastName();
    },this);
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

我有点不太理解fullName里function最后的this是什么作用,function的参数?还是别的?
它指向的是谁?该怎么可以透彻的理解这个语句?
我经常对匿名function(){}后面直接加参数这种行为理解不能,有没有什么好的文章介绍相关的内容?

谢谢大家

阅读 4k
7 个回答

关于 this,我已经在JavaScript 的 this 指向问题深度解析 进行了详细的讲述,所以这里就不重复了。

具体到这个问题,是关于 ko.computed() 的 API,看看从官方文档摘取的一段:

Managing ‘this’

The second parameter to ko.computed (the bit where we passed this in the above example) defines the value of this when evaluating the computed observable. Without passing it in, it would not have been possible to refer to this.firstName() or this.lastName(). Experienced JavaScript coders will regard this as obvious, but if you’re still getting to know JavaScript it might seem strange. (Languages like C# and Java never expect the programmer to set a value for this, but JavaScript does, because its functions themselves aren’t part of any object by default.)

大致翻译一下第一句就是:ko.computed 的第二个参数指定在执行 computed 观察函数时的 this

所以在 ko.computed(function() {...}, this) 这里传入的 this,就是在 function() {...} 使用的 this,即 this.firstName()this.secondName() 的那个 this。也就是 AppViewModel 作用域中的 this

这个其实是js函数基础,你需要一本红宝书(Javascript高级程序设计),Function 部分

1.要理解这里的this指向哪里,只需要理解函数作为构造函数之后,也就是放在new 关键字之后发生了什么
2.其实这里的this是指向AppViewModel new出来的对象,可以参考https://developer.mozilla.org...
3.匿名函数就是一个函数,只不过这个函数不需要在其他地方调用,所以不需要有一个名字,在JavaScript里函数是一等公民,也是对象,可以作为参数传递


// ko.computed大概是这样执行的
ko.computed = function(fn, context) {
    return fn.call(context)
}

this.fullName = ko.computed(function(){
    return this.firstName() + " " + this.lastName();
}, this);

computed的第二个参数可以让我们指定上下文

这里是指向实体对象的
而且这里AppViewModel其实是定义了一个类似类的东西,它可以new出一个对象来,这个对象就可以有具体的一些属性了。

我回一个没有文档时怎么判断吧,毕竟this和函数call apply bind也有关
一个debugger就知道了
this.__proto__ === ko.constructor.prototype;
this.__proto__ === AppViewModel.prototype;

兄弟那个函数叫自执行函数 格式为(function(){})()这是一般格式 现在有es6了 所以也可以写成:
(()=>{})()箭头函数。 至于你说的有关于this指向的问题,我觉得这个你得先系统的去学this有指向window的,也有指向当前对象的,还有指向当前函数的,在回调函数中的this指向window。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题