Javascript:使对象继承数组方法
Javascript: make an object inherit array methods
var RPNCalculator = function() {
this.stack = [];
this.total = 0;
this.value = function() {
return this.total;
}
this.push = function(val) {
this.stack.push(val);
}
this.pop = function() {
this.stack.pop();
}
this.process = function() {
this.val1 = this.stack.pop();
this.val2 = this.stack.pop();
this.total = 0;
}
this.plus = function() {
this.process();
this.total = this.val1 + this.val2;
this.stack.push(this.total);
}
this.minus = function() {
this.process();
this.total = this.val2 - this.val1;
this.stack.push(this.total);
}
}
如何使RPNCalculator对象继承数组方法,而不自己创建推送和弹出方法?例如,如果我执行以下
rpnCalculator = new RPNCalculator();
rpnCalculator.push(2);
它将把数字2添加到堆栈数组
如果您想要Array
提供的所有方法,可以从使用Object.create
从Array
继承原型开始,然后将自定义函数添加到新的构造函数原型中。
var Foo = function () {};
Foo.prototype = Object.create(Array.prototype);
Foo.prototype.process = function process() {
// `this` is the array
// Do some logic...
// returning `this` to show it is the array
return this;
}
var foo = new Foo();
foo.push(3);
foo.push(2);
foo.push(1);
document.write(
'<h3>foo</h3>' +
'<pre>' + JSON.stringify(foo, null, 4) + '</pre>' +
'<h3>foo.process()</h3>' +
'<pre>' + JSON.stringify(foo.process(), null, 4) + '</pre>'
);
你可以做:
this.push = this.stack.push.bind(this.stack);
this.pop = this.stack.pop.bind(this.stack);
这只需要使用stack
的方法,而不是定义自己的方法。
相关文章:
- javascript:更改应用到的数组的数组方法列表
- 使用Knockout.js的数组方法将地图标记添加到Google地图
- 模拟 javascript 的数组方法.面向对象的Javascript,作者:Stoyan Stefanov
- ECMA5 数组方法 - 查找数组中某个类型的第一个对象
- 在 Object.prototype 上为 NodeList 对象实现数组方法是否是一个很好的实践?
- 有没有一种方法可以实现chain.push和.shift数组方法
- 'document.getElementsByClassName' 的结果没有定义像 'map' 这样的数组方法,即使它
- JavaScript重写数组方法
- 有谁能告诉我在Shift的引擎盖下发生了什么吗?JavaScript中的Unshift()数组方法
- 如何删除数据库使用数组方法DELETE
- .push数组方法不工作角过滤器
- 包含数组方法的JavaScript函数没有返回期望的结果
- 对象/数组方法:修改原始的还是创建新的?指导方针
- 用自定义方法替换本机对象(数组)方法:是否安全?兼容的
- Javascript数组方法查找超过第一个值的indexOf
- 数组方法"some"的使用:收到意外的结果
- Javascript:使对象继承数组方法
- 使用数组方法遍历列表项
- 使用数组方法时返回方括号的函数
- 数组方法和连接函数组合输出在 javascript 中无法理解