简体   繁体   English

使用默认函数扩展JavaScript对象

[英]Extend a JavaScript object with a default function

In google app scripts I have a one dimensional data array that I can get values from like this: 在谷歌应用程序脚本中,我有一个一维数据数组,我可以从这里获取值:

data[0]

I'd love to be able to pass in the column name instead like this: 我希望能够传递列名,而不是这样:

data("A")

That way I don't have to convert letters into their array position. 这样我就不必将字母转换成数组位置。 So I'd like to extend the array object (extending isn't really risky since it's running in an isolated script environment). 所以我想扩展数组对象(因为它在一个独立的脚本环境中运行,所以扩展并不存在风险)。

I know I can add a function to the array prototype using this letter to number function and this object extension question like this: 我知道我可以使用这个字母数字函数向数组原型添加一个函数,这个对象扩展问题如下:

 Array.prototype.byCol = function(colName) { return this[getColumnNumber(colName) - 1]; } function getColumnNumber(str) { var out = 0, len = str.length; for (pos = 0; pos < len; pos++) { out += (str.charCodeAt(pos) - 64) * Math.pow(26, len - pos - 1); } return out; } var data = [1,2,3,4]; document.write(data.byCol("B")); 

But this is a slightly bulkier calling syntax than I wanted. 但这是一个比我想要的稍微笨重的调用语法。

Based on this question on default functions , it looks like it's possible to assign a default function to an object, but they're doing so by just creating a function object like this: 基于关于默认函数的这个问题,看起来可以为对象分配一个默认函数,但他们只是通过创建一个这样的函数对象来实现:

var test = new func(function() {
    // do something
});

Can I get extend the array so that it will execute a default function when called as a method? 我可以扩展数组,以便在作为方法调用时执行默认函数吗?

Put simply, you can't make something into a function if it's not already a function, and you can't really extend arrays. 简而言之,如果它不是一个函数,你就无法将某些东西变成函数,并且你无法真正扩展数组。

What you can do is create a wrapper function that wraps an array and provides the functionality you want, and also include the ability to get back the original array if you need it: 你可以做的是创建一个包装器函数,它包装一个数组并提供你想要的功能,还包括在需要时恢复原始数组的能力:

 var wrapper = (function() { function getColumnNumber(str) { return Array.prototype.reduce.call(str.toUpperCase(), function (t, c) { return 26 * t + c.charCodeAt(0) - 64; }, 0) - 1; } return function(arr) { return function(col, val) { if (arguments.length === 0) { return arr; } if (arguments.length > 1) { arr[getColumnNumber(col)] = val; } return arr[getColumnNumber(col)]; }; }; })(); var w = wrapper([10, 20, 30, 40, 50]); snippet.log(w('D')); // 40 w('D', 33); // set value snippet.log(w('D')); // 33 w()[3] = 42; // access underlying array directly w().push(60); snippet.log(w('D')); // 42 snippet.log(w('F')); // 60 
 <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

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

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