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

查看:21
本文介绍了具有原型与闭包的面向对象的 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())

对比

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天全站免登陆