开发者

JavaScript: How to set a property for a function?

开发者 https://www.devze.com 2023-02-28 23:56 出处:网络
I\'m testing one of my functions, and I want to test whether a specific function is called with the right argument from that code.

I'm testing one of my functions, and I want to test whether a specific function is called with the right argument from that code.

For that reason, I overwrite the original function like this:

var oldSort = sort;
sort = function(array) {
    this.arrayToSort = array;
}

Then I execute it and check that the property sort.arrayToSort is set to the value I passed in and reassign the original function:

sort(myArray);
deepEqual(myArray, sort.arrayToSort); 
sort = oldSort;

However, I can't access sort.arrayToSort like that. How can I set a property of the function to make that possible? Right now, I'开发者_开发技巧m declaring a variable above the sort function and have it set that, but I'd rather have it as a property of the function to keep its scope small. Is that possible?


Sounds like you want arguments.callee, which refers to the function itself, rather than the object it was bound to.

var oldSort = sort;
sort = function(array) {
    arguments.callee.arrayToSort = array;
}


you cant access the function properties if you don't create it with new keyword.

mysort = new sort(array);
alert(mysort.arrayToSort);

you can use custom comparator function in original sort. like this

array.sort(sortfunction)

function sortfunction(a, b){
   //Compare "a" and "b" in some fashion, and return -1, 0, or 1
}
0

精彩评论

暂无评论...
验证码 换一张
取 消