本文介绍了2个JavaScript对象之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试提高我的JavaScript技能.我不明白为什么(5)可以工作,而(2)返回错误.不一样吗?
(1)-B.fn()//确定
(2)-B.fn2()//TypeError:对象#没有方法``fn2'';
(3)-var a = new A()
(4)-a.fn()//确定
(5)-a.fn2()//确定
I try do improve my JavaScript skills. I don''t understand why (5) works and (2) returns error. Isn''t the same?
(1) - B.fn() //OK
(2) - B.fn2() //TypeError: Object # has no method ''fn2'';
(3) - var a = new A()
(4) - a.fn() //OK
(5) - a.fn2() //OK
var A = function () {
this.fn = function () { alert(3); }
}
A.prototype = {
fn2: function () { alert(4); }
};
var B =
{
fn: function () { alert(1); }
}
B.prototype = {
fn2: function () { alert(2); }
};
推荐答案
A = function() {
//This is the constructor.
};
A.prototype = {
//This prototype object contains a definition of the functions on your class.
fn: function() {
alert(1);
}
};
然后以这种方式实例化对象;
You then instantiate an object in this way;
var a = new A();
a.fn();
我建议您阅读 Douglas Crockford的教程 [ ^ ].
I recommend you read some of Douglas Crockford''s tutorials[^].
这篇关于2个JavaScript对象之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!