为什么原型JavaScript在这种情况下不起作用
why prototype javascript not works in that case
我的情况(为什么"test1"没有出现在警报窗口中):
var Parent=function(){
this.test1= function(){
alert("test1");
}
}
var Child=function(){
this.prototype=new Parent();
}
var test=new Child();
test.test1();
http://jsfiddle.net/c3sUM/2/(在线尝试相同的代码)
谢谢
问题是你没有分配Child
的原型,而是在Child
的实例中做了一个属性prototype
,该属性指向Parent
的实例。
相反,请执行此操作:
var Child = function(){}; // create constructor
Child.prototype = new Parent(); // assign instance of parent to constructor's
// prototype
类似的答案可能会有所帮助
使用函数声明,您的代码会更清晰:
// Parent constructor
function Parent() {}
// Methods of Parent.prototype are inherited by
// instances of parent
Parent.prototype.test1 = function() {
alert('test 1');
}
// Child constructor
function Child(){}
// Make Child.prototype an instance of Parent so
// instances inherit from Child and Parent
Child.prototype = new Parent();
// Instance inherits from Child (and hence Parent);
var child = new Child();
child.test1(); // 'test 1'
在这种情况下,使用函数表达式而不是声明的唯一原因是,如果要基于其他逻辑动态创建构造函数。
相关文章:
- 为什么jQuery悬停方法在这种情况下不起作用
- 为什么push方法没有'在这种情况下不起作用:[].推
- 倒计时在某些情况下不起作用
- res.download()在我的情况下不起作用
- 为什么getElementbyId在这种情况下不起作用
- $animate.removeClass 在没有 $evalAsync inside 指令的情况下不起作用
- 为什么 array.indexOf(undefined) 在数组稀疏的情况下不起作用
- 多次点击功能在不重新加载页面的情况下不起作用
- 数据绑定在特定情况下不起作用(AngularJS)
- 为什么原型JavaScript在这种情况下不起作用
- 为什么隐藏/显示(向上滑动/向下滑动)在这种情况下不起作用
- 为什么表单序列化在这种情况下不起作用
- Jquery .hide在这种情况下不起作用
- 为什么'this'在这种情况下不起作用
- 为什么我的正则表达式在这种特殊情况下不起作用
- 为什么jQuery元素[]选择器在这种情况下不起作用?
- 为什么td最大宽度在这种情况下不起作用
- 为什么 closest() 选择器在这种情况下不起作用
- 为什么点击
在这种情况下不起作用 - AngularJs$无效;在这种情况下不起作用