2个JavaScript对象之间有什么区别? [英] What's the difference between 2 JavaScript objects?

查看:65
本文介绍了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); }
};

推荐答案

您的B对象未使用new关键字初始化.使用new关键字初始化对象时,原型上的函数将应用于所得对象.在JavaScript中定义类的正确方法是:

Your B object wasn''t initialised using the new keyword. When you initialise an object using the new keyword, the functions on the prototype will be applied to the resulting object. The correct way to define a class in JavaScript is:

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对象之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆