javascript - 请问这样创建对象有什么效果吗?

标签 javascript object constructor

    <!doctype >
<html>
<meta utf="utf-8">
<header>
    <title>PRACTISE</title>
    <script >

function MakeMe(name , age , likes, shout){ //creates objects
    return {
        name : name,
        age : age,
        likes : likes,
        shout : function(){
            alert(shout + " " +last(this.likes));
        }
    }
}

function last(obj){ //gets last element of the array
    var el=obj.pop();
    obj.push(el);
    return el;
}

var dammy = MakeMe("Damilola" , 20, ["Jesus" , "Programming"], "Ewooooooo");//creates an object

dammy.shout();

var dara = MakeMe("Daramola" , 17, ["God" , "Gaming" , "Ed sheeran"] , "Leaveeeeeeeeeeee");//creates an object

// i wrote the following codes below to check if dammy and dara are really different objects
alert(last(dara.likes));
dara.shout();
dammy.likes.push("Taylor");
alert(last(dara.likes));
alert(last(dammy.likes));
dammy.shout();
    </script>
    </head>
</html>

我的主要问题是:与使用构造函数和使用“new”关键字的常规方法相反,这是一种在 javascript 中创建对象的好方法吗?如果使用上述方法创建对象有任何副作用。谢谢你

    //Normal way is
function MakeMe(name ,age, likes, shout){
   this.name = name;
   this.age= age;
   this.likes={"me", "you", "us"};
   this.shout = function(){
                alert(shout + " " +last(this.likes));
            };
}

var dammy = new MakeMe("D" , 17, ["God" , "Gaming" , "Lorde"] , "Loveee");

最佳答案

有一个区别,这个区别在于你返回的对象的原型(prototype)。第二种方式,使用 new 创建一个继承自 MakeMe 函数的 prototype 的对象,而使用 {} 的第一种方式只创建一个与 MakeMe 完全无关的独立对象。

我已经在两个简化的示例中展示了这一点。

function Make1(value) {
  return {prop: value};
}

// Construction using {} returns a simple object that inherits nothing from Make1.
var object1 = Make1('foo');

// So I can add methods all I want...
Make1.prototype.showMe = function() {
  alert(this.prop);
}

// But object1 won't get them, and the line below shows that the method is not assigned.
alert(typeof object1.showMe);

// ..  and the line below will fail.
object1.showMe();

function Make2(value) {
  this.prop = value;
}

// Construct 'new' returns an object that inherits everything from the prototype of Make2.
var object2 = new Make2('bar');

// I can now add a method to the prototype.
Make2.prototype.showMe = function() {
  alert(this.prop);
}

// And call that method for the object and any other object that was constructed
// this way. They all share this common behaviour now.
object2.showMe();

现在这本身不是问题。这只是取决于你在特定情况下需要什么,你可以在你的项目中使用两者。

我不记得是从哪里学来的,所以我查找了一些“随机”来源,这些来源似乎很好地解释了这种原型(prototype)设计。

关于javascript - 请问这样创建对象有什么效果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27633639/

相关文章:

javascript - 查找所有字母而不重复正则表达式

.net - 从异常类派生是在 C# 中创建对象 'throwable' 的唯一方法吗?

ios - 在 iPad 的存储空间中存储 1000 多张图像

java - Guava:图表的复制构造函数

php - 在类定义的 Constructor VS 中设置变量

javascript - 从浏览器中隐藏 Javascript 错误消息

javascript - jquery html() vs empty().append() 性能

javascript - 比较最多三个日期选择器字段中的日期,然后用最早的字段填充另一个字段

JavaScript 继承 Object.call() 未定义

c++ - std::vector、构造函数、对象