这两个代码示例有什么区别? [英] What is the difference between these two code samples?

查看:65
本文介绍了这两个代码示例有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码1:

var Something = {
name: "Name",
  sayHi: function(){
     alert(Something.name);
  }
}

代码2:

 function Something(){
    this.name = "Name";
 }

 Something.prototype.sayHi = function(){
    alert(Something.name);
 }

编辑:
所以,伙计们,你的意思是第二个更好?或者更正式?

So, Guys, you mean the Second one is better? or more "formal" ?

推荐答案

基本上在第一个例子中,您声明了一个 object literal ,它实际上已经是一个对象实例。

Basically in the first example you declare an object literal which is actually already an object instance.

在第二个示例中,您定义了一个构造函数,该函数可以与一起使用。用于创建对象实例的 new 运算符。

In your second example, you define a constructor function which can be used with the new operator to create object instances.

对象文字也可用于创建新的实例对象和原型继承,道格拉斯克罗克福德也提倡这种技术。

Object literals can be also used to create new instances of objects and do prototypal inheritance, Douglas Crockford promotes also this technique.

基本上你可以有一个对象运算符:

Basically you can have an object operator:

function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
}

这个辅助函数可以非常直观和方便的方式使用。

This helper function can be used in a very intuitive and convenient way.

它基本上接收一个对象作为参数,在函数内部创建新对象实例,旧对象链接到新对象的原型,并返回它。

It basically receive an object as a parameter, inside the function a new object instance is created, the old object is chained to the new object's prototype, and its returned.

它可以像这样使用:

var oldObject = {
  firstMethod: function () { alert('first'); },
  secondMethod: function () { alert('second'); },
};

var newObject = object(oldObject);
newObject.thirdMethod = function () { alert('third'); };

var otherObject = object(newObject);
otherObject.firstMethod();

您可以根据需要继续前进,从之前定义的对象中创建新实例。

You can go further as you want, making new instances from the previously defined objects.

推荐:

  • Prototypal Inheritance in JavaScript
  • Advanced JavaScript (Video)

这篇关于这两个代码示例有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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