function A(){}
A.prototype = {
aa : function(){
console.log(1)
}
}function B(){ }
B.prototype = {
bb : function(){
console.log(2)
}
}B.prototype = new A();
var b = new B();
B.prototype.constructor = B; // 不加这个的时候 b指向的object 报错说object 没有bb这个方法,加上这话以后 我让他指向B 但是无效 还是报下面的错误b.aa();
b.bb(); //报错 没有这个方法请问两个问题
1 b.bb(); 这个为什么不能访问 怎么才能访问 ,自己的实列 虽然prototype指向了A ,但是我用constructor 指回自己的时候 还是不能访问啊
2 B.prototype.constructor = B; 这句话怎么用?在哪用才有效JavaScriptPrototype继承原型
A.prototype = {
aa : function(){
console.log(1)
}
}function B(){ }
B.prototype = {
bb : function(){
console.log(2)
}
}B.prototype = new A();
var b = new B();
B.prototype.constructor = B; // 不加这个的时候 b指向的object 报错说object 没有bb这个方法,加上这话以后 我让他指向B 但是无效 还是报下面的错误b.aa();
b.bb(); //报错 没有这个方法请问两个问题
1 b.bb(); 这个为什么不能访问 怎么才能访问 ,自己的实列 虽然prototype指向了A ,但是我用constructor 指回自己的时候 还是不能访问啊
2 B.prototype.constructor = B; 这句话怎么用?在哪用才有效JavaScriptPrototype继承原型
B.prototype = new A();
B.prototype = {
bb : function(){
console.log(2)
}
}这样就可以了
function B(){ }
B.prototype = new A();
B.prototype.bb = function(){
console.log(2)
}或者function B(){ }
B.prototype = {
bb : function(){
console.log(2)
}
}
foreach(var i in new A()) {
B.prototype[i] = A[i];
}
B.prototype.constructor = B; 换下位置
function B(){ }
B.prototype = new A();
B.prototype.bb = function(){
console.log(2)
}或者function B(){ }
B.prototype = {
bb : function(){
console.log(2)
}
}
foreach(var i in new A()) {
B.prototype[i] = A[i];
}但是那样就不能再调用aa方法了,B.prototype = new A(); 后在重新 设置B.prototype的值 那上一句B.prototype = new A(); 其实没有任何意义了 。
至于constructor属性,它只是原型对象中的一个属性而已,和b能不能调用bb没有关系。可以理解为:b原来的原型对象为:{constructor:B, bb:function(){...}},而后又变成了{constructor:A, aa:function(){...}},
最终在你把constructor改变后变成了: {constructor:B, aa:function(){...}}。虽然constructor变了回来,但是原型对象里的方法还是aa。所以实例化后的b只能调用aa,不能调用bb。2.constructor的本意是在指明一个实例所属的类(构造函数),但是因为该属性可以被随意改变,就像你上面的操作一样(B.prototype.constructor = B),所以实际上,该属性在一般情况下并没有多大用处(个人理解,仅供参考)。
A.prototype.a = function(){ console.log(1) }
function B(){}
B.prototype = new A();
B.prototype.b = function(){ console.log(2) }
var t = new B();
t.a(); // 输出1
t.b(); // 输出2
这样又是为什么呢?
A.prototype.a = function(){ console.log(1) }//给A增加一个a函数
function B(){}
B.prototype = new A();//给B增加一个a函数
B.prototype.b = function(){ console.log(2) }//给B增加一个b函数
var t = new B();这代码是增加函数,没有覆盖,可以理解为如下代码
function B(){}
B.prototype.a = function(){ console.log(1) };//给B增加一个a函数
B.prototype.b = function(){ console.log(2) }//给B增加一个b函数
var t = new B();
t.a(); // 输出1
t.b(); // 输出2
同时增加a和b函数,这里没有覆盖。