覆盖方法的 JavaScript 原型调用基方法
javascript prototype overriding a method calls the base method
>我有三个对象相互扩展。基地 -> A ->子 A。它们在原型中都有方法测试。当我调用 A.test 或 childA.test 时,将调用 Base.test。我想知道每个对象调用自己的方法的选项是什么。这是代码:
$(document).ready(function(){
function Base(){
};
Base.prototype.test = function(){
console.log("base");
};
function A(){
};
A.prototype.test = function(){
console.log("A");
};
function ChildA(){
};
ChildA.prototype.test = function(){
console.log("ChildA");
};
var base = new Base();
var a = new A();
var childA = new ChildA();
$.extend( a, base );
$.extend( childA, a );
a.test();
childA.test();
}
);
和小提琴:http://jsfiddle.net/pjWjy/84/
所以当我打电话给base.test - > log base; a.test -> log a; childA -> log childA;
这不是你在 JavaScript 中使用构造函数进行原型继承的方式(它根本不是继承,只是在实例之间复制方法)。使用任何标准继承模式,您都会得到正确的test
。
下面是一个示例:
// On old browsers like IE8, we need to shim Object.create
if (!Object.create) {
Object.create = function(proto, props) {
if (typeof props !== "undefined") {
throw "The second argument of Object.create cannot be polyfilled";
}
function ctor() { }
ctor.prototype = proto;
return new ctor();
};
}
// Define our Base constructor
function Base() {
}
// Define Base#test
Base.prototype.test = function() {
snippet.log("Base#test");
};
// Derive A from Base
function A() {
Base.call(this);
}
A.prototype = Object.create(Base.prototype);
A.prototype.constructor = A;
// Define A#test
A.prototype.test = function() {
snippet.log("A#test");
};
// Derive ChildA from A
function ChildA() {
A.call(this);
}
ChildA.prototype = Object.create(A.prototype);
ChildA.prototype.constructor = ChildA;
// Define ChildA#test
ChildA.prototype.test = function() {
snippet.log("ChildA#test");
};
// Run
var b = new Base();
b.test();
var a = new A();
a.test();
var ca = new ChildA();
ca.test();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
如果你打算用构造函数做很多这样的继承,你可能会对我的帮助程序脚本Lineage
感兴趣,它使事情更加简洁和包含,并简化了"超级调用"(链接到方法的父版本)。但是,当然,该脚本很快就会因ES6的class
功能而过时。
相关文章:
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- javascript从子方法调用父方法
- 我应该返回一个类似console.log()的方法调用吗
- NodeJS-从同一文件中的另一个方法调用一个方法
- 使用restangular save方法调用put与post时的控件
- 从实例方法调用实例方法
- Node.js-异步方法调用问题
- Jquery事件绑定获胜'当作为方法调用时不起作用,但当直接在控制台中调用时会起作用
- 向模板实例变量传递调用方法调用的结果时出现异常
- jQuery 方法调用了两次
- 不能从 Backbone.View 的方法调用 Backbone.collection 的方法,其中包含 require
- 组合 onLayout 的方法调用
- lodash/下划线 - 使用绑定与方法调用和方法保持未绑定
- 从公共方法调用模块的私有函数
- 如何对 jqGrid 的 loadComplete 和 onSelectRow 进行基因预和后方法调用
- 完全限定的 JavaScript 方法调用
- 为什么我在 Angular JS 中收到两个方法调用
- 如何在从排序方法调用参数时将其传递给回调
- 使用两种不同的方法调用方法
- 如何在 javascript 中更改方法调用的全局范围