对象字面量vs构造函数+原型 [英] Object literal vs constructor+prototype

查看:177
本文介绍了对象字面量vs构造函数+原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数 =用于创建的函数

使用关键字new的多个实例。



原型 >这是我到目前为止所了解的。但是我研究的越多,我越来越困惑他们每个人的意义是什么。
我在我的代码中使用了构造函数,原型和文字几次。但是每次我使用它们,我觉得我还是不知道它的全部潜力<我现在想成为一个开始的一步。我希望在stackoverflow的人帮助我实现它


  1. 最好的编程方式( object
    literals vs constructors vs prototype

    可以使用构造函数和原型,只使用对象字面量
    而不使用构造函数和原型来编写代码。


  2. 匿名功能的意义。


这是一个非常简单的例子,我也知道他们是什么,但我不知道他们可以做什么可能的魔法。

解决方案

是一个(在我看来基本的)对象字面量和函数之间的区别,私有变量。由于对象不能被实例化(因为它已经是 Object 的实例),它不可能有自己的(新的)范围 。它是高级JS编程的基本概念。有一个新的范围允许你做几乎所有的事情(你可以声明自己的窗口文档您自己范围内的JS 关键字)。现在,一些简单的例子:



让我们假设你想创建同一个对象的大量实例(尽可能少的行):

  function MyObj(i){
var privateCounter =我是实例化的对象+ i +。
this.counter = function(){
return privateCounter;
};
}

var MyObjList = [],
ObjLitList = [];
for(var i = 0; i <100; i ++){
MyObjList.push(new MyObj(i));
ObjLitList.push({counter:I is the literal object number+ i +。
}

现在你有200个对象,几乎但不是精确,同样的事情。您可以根据需要扩展它们,因为函数对象,但是在函数的情况下,您不能直接访问 private 变量。让我们看看函数的优点:




  • 它被视为一个 Object

  • 它有自己的原型

  • 它有私有变量



Object s?




  • 对象

  • Prototype ,但您可以声明函数并扩展对象本身

  • 没有私有变量



除了私有变量,它们彼此没有太大的不同。



函数的原型可以做:

  MyObj.prototype.setX = function(x){
this.x = x;
}

使用原型可以创建一个匿名的实例函数(可以命名为,然后分配),它将在实例之间共享。

 函数setX(x){
this.x = x ;
}
var obj = {
setX:setX
};

正如你所看到的,你必须创建一个对象,每次定义一个属性 setX 。否则,你可以扩展 Object.prototype 本身(但是关于扩展原生JS对象的原型有很长的争论)。



那么最好是什么?没有人,这取决于你要做什么,你从脚本中需要什么,哪两个你感觉更舒服。



我更喜欢写我的自己的函数,并像类一样对待它们,因为它们更加可读,我可以使用私有变量。我不知道任何人使用文字而不是函数。



至于问题:


这是最好的编程方法(对象字面量vs构造函数对原型)





可以使用构造函数和原型来编写代码,而不使用构造函数和原型。


是的,你可以如果你不需要私有变量(如果脚本不是太大,想象一下jQuery写成一个对象字面量:D)。

$ b


好吧,我可以回答一个例子:

  // code 
myNamedFunction
// code
function myNamedFunction(){
alert(I'm defined everywhere!:));
}

这样做不会产生 TypeError

  myAnonymousFunction 
var myAnonymousFunction = function(){
alert(我在此声明后定义:);
}
myAnonymousFunction(); // works!

这将导致未捕获TypeError:undefined不是函数,因为 myAnonymousFunction 只是有效函数的引用(未命名,因此不能从脚本调用)。



这个参数有很多事情要说,开始高级编程的好处是 Javascript Garden 。其他良好的读数包括 JS中的OOP基本知识 - NetTutsPlus 使用对象 - MDN JS - Phrogz中的OOP



希望此帮助!



Sidenote:函数也有一个很好的优势,因为他们可以改变它们的上下文( this )函数(例如 call ),而对象不能。


Object literal=name value pairs wrapped in curly braces.

Constructor=a function used to create multiple instance using keyword new.

Prototype=for extension of a literal.

This is what I have understood till now.But the more I research,More I get confused about what is the significance of each one of them. I have used constructor,protoypes and literals in my code a few times.But everytime I use them,I feel like I am still not aware of the full potential of it.I want to go one step ahead of being a begineer now.I hope Folks at stackoverflow help me achieve it

  1. Which is the best preferred way of programming(object literals vs constructors vs prototype)

  2. can a code with constructor and protoype be written using just object literals without using constructor and protoype.

  3. what is the signifiance of anonymous function.

A very simple example demonstrating their importance will also do.I am aware of what they are but I am not aware of what possible magic they can do.

解决方案

There is a (fundamental, in my opinion) difference between object literals and functions, the "private" variables. Since an object can't be instantiated(because it is already an instance of Object) it has no possibility to have its own (new) scope. It is a base concept of advanced JS programming. Having a new scope allows you to do almost everything(you can declare your own window, document or whatever you want except the JS keywords inside your own scope). Now, some simple examples:

Let's assume you want to create a large number of instances of the same object(using as few lines as possible):

function MyObj(i) {
    var privateCounter = "I am the instantiated object " + i + " .";
    this.counter = function() {
        return privateCounter;
    };
}

var MyObjList = [],
    ObjLitList = [];
for (var i = 0; i < 100; i++) {
    MyObjList.push(new MyObj(i));
    ObjLitList.push({counter: "I am the literal object number " + i + "."});
}

Now you have 200 objects that are almost, but not precisely, the same thing. You can extend them as you prefer, because functions are objects, but in the case of the function you cannot access the private variable directly. Let's see which are the advantages of a function:

  • It is treated like an Object
  • It has its own Prototype
  • It has private variables

And the Objects?

  • It is an Object
  • It doesn't have its own Prototype, but you can declare the functions and extend the object itself
  • It doesn't have private variables

Apart the private vars, they are not much different from each other.

Let's see what a function's prototype can do:

MyObj.prototype.setX = function(x) {
    this.x = x;
}

Using the prototype allows you to create an only instance of an anonymous function(which can be named too and then assigned) which will be shared across instances. How can you do the same thing with object literals?

function setX(x) {
    this.x = x;
}
var obj = {
    setX: setX
};

As you can see you have to create the object defining everytime a property which is setX. Otherwise, you can extend Object.prototype itself(but there is a long debate about extending the prototype of native JS objects).

So which is the best way? There is no one, it depends on what you have to do, what you need from your script, which of the two you feel more comfortable with.

I prefer writing my own functions and treat them like classes, because they are more readable and I am able to use "private" variables. I don't know anyone using literals instead of functions though.

As for the questions:

Which is the best preferred way of programming(object literals vs constructors vs prototype)

Answered.

can a code with constructor and protoype be written using just object literals without using constructor and protoype.

Yes, you can if you don't need private variables(and if the script isn't too big. Imagine jQuery written as an Object literal :D).

what is the signifiance of anonymous function.

Oh well, I can answer with an example:

//code
myNamedFunction();
//code
function myNamedFunction() {
    alert("I'm defined everywhere! :)");
}

This works and won't generate a TypeError.

myAnonymousFunction();
var myAnonymousFunction = function() {
    alert("I'm defined after this declaration :(");
}
myAnonymousFunction(); // works!

This will cause a Uncaught TypeError: undefined is not a function, because myAnonymousFunction is only a reference to the effective function(which is unnamed, so it is not callable from the script).

There are a lot of things to say about this argument, and a good point to start advanced programming is Javascript Garden. Other good readings are Basics of OOP in JS - NetTutsPlus, Working with Objects - MDN and OOP in JS - Phrogz

Hope this helps!

Sidenote: functions also have a good advantage since they can change their context(this) just with a function(call for example), while objects can't.

这篇关于对象字面量vs构造函数+原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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