面向对象的javascript与原型和闭包 [英] Object oriented javascript with prototypes vs closures

查看:114
本文介绍了面向对象的javascript与原型和闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇以下OOP javascript技术之间的区别。他们似乎最终做同样的事情,但被认为比另一个更好?

I'm curious what the difference is between the following OOP javascript techniques. They seem to end up doing the same thing but is one considered better than the other?

function Book(title) {
    this.title = title;
}

Book.prototype.getTitle = function () {
    return this.title;
};

var myBook = new Book('War and Peace');
alert(myBook.getTitle())

vs

function Book(title) {
    var book = {
        title: title
    };
    book.getTitle = function () {
        return this.title;
    };
    return book;
}

var myBook = Book('War and Peace');
alert(myBook.getTitle())


推荐答案

第二个并不真正创建实例,它只返回一个对象。这意味着您无法利用 instanceof 等运算符。例如。在第一种情况下你可以 if(myBook instanceof Book)来检查变量是否是Book的类型,而第二个例子则会失败。

The second one doesn't really create an instance, it simply returns an object. That means you can't take advantage of operators like instanceof. Eg. with the first case you can do if (myBook instanceof Book) to check if the variable is a type of Book, while with the second example this would fail.

如果你想在构造函数中指定你的对象方法,这是正确的方法:

If you want to specify your object methods in the constructor, this is the proper way to do it:

function Book(title) {
    this.title = title;

    this.getTitle = function () {
        return this.title;
    };
}

var myBook = new Book('War and Peace');
alert(myBook.getTitle())

虽然在这个例子中两者都表现得准确同样,也有差异。使用基于闭包的实现,您可以拥有私有变量和方法(只是不要在 this 对象中公开它们)。所以你可以这样做:

While in this example the both behave the exact same way, there are differences. With closure-based implementation you can have private variables and methods (just don't expose them in the this object). So you can do something such as:

function Book(title) {
    var title_;

    this.getTitle = function() {
        return title_;
    };

    this.setTitle = function(title) {
        title_ = title;
    };

    // should use the setter in case it does something else than just assign
    this.setTitle(title);
}

Book函数之外的代码无法直接访问成员变量,他们有使用访问者。

Code outside of the Book function can not access the member variable directly, they have to use the accessors.

其他重大差异是性能;由于使用闭包包含一些开销,基于原型的分类通常要快得多。您可以在本文中了解性能差异: http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspx

Other big difference is performance; Prototype based classing is usually much faster, due to some overhead included in using closures. You can read about the performance differences in this article: http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspx

这篇关于面向对象的javascript与原型和闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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