简体   繁体   English

在javascript qunit中模拟'this'

[英]Mocking 'this' in javascript qunit

if i have a Javascript function that uses, something like this... $(this)[0].element.id; 如果我有一个使用的Javascript函数,例如... $(this)[0].element.id;

updateElement(){
$(this)[0].element.id;
}

I am using Qunit, is there a way i can mock 'this' I would like to be able to test this function. 我正在使用Qunit,有没有一种方法可以模拟'this'我希望能够测试此功能。

With the functions apply or call of the Function object, you can change the value of this when calling a function: 随着功能的applycall的的Function对象,你可以改变的值, this调用函数:

var mock = ...

updateElement.call(mock);

this will refer to mock inside the updateElement call above. this将引用上面的updateElement调用中的mock

I assume, that this refers to some jQuery Object. 我假设this是指一些jQuery对象。 You could create the respective objects using the jQuery function and then use bind() to attach the object as this to your actual function: 你可以创建一个使用jQuery的功能各自的对象,然后用bind()对象作为连接this对您的实际功能:

// prepare the DOM objects
var $elem = $( '...' );

// prepare a bound function
var boundFct = updateElement.bind( $elem );

// execute your function
boundFct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM