这些看似相似的JS代码有什么区别?

时间:2013-12-30 10:25:15

标签: javascript

我是JS& amp;的新来者绕着它工作。 我试图测试我的JS技能,所以我决定写下一个简单的代码,在控制台中显示员工信息,实际上我写了它,但与我从2个教程中学到的不同,第一个解释“如何创建对象和方法“和第二个解释”原型对象“。虽然,结果非常相同。 所以,如果有人能帮我理解差异,我将非常感激。


重要!!

  • 如果您想测试代码,请打开控制台!
  • 我无法将链接粘贴到第三个代码,因为我仍然没有enought信誉点来发布超过2个链接。遗憾。

这是使用我的方法的项目(JSFIDDLE:http://jsfiddle.net/9NUGC/

var peter = {name:"Peter", age:"23", sex:"Male", country:"Russia", position:"Manager"};
var mark = {name:"Mark", age:"21", sex:"Male", country:"US", position:"Designer"};
var jessica = {name:"Jessica", age:"19", sex:"Female", country:"UK", position:"Programmer"};

function showDetailsInLog(x){
    console.log("Employee Name: " + x.name);
    console.log("Employee Age: " + x.age);
    console.log("Employee Sex: " + x.sex);
    console.log("Employee Country: " + x.country);
    console.log("Employee Position: " + x.position);
    console.log("-----------------------");
}

showDetailsInLog(peter);
showDetailsInLog(mark);
showDetailsInLog(jessica);

这是使用“创建对象和方法”教程中的方法的项目(JSFIDDLE:http://jsfiddle.net/s5d64/

var peter = {name:"Peter", age:"23", sex:"Male", country:"Russia", position:"Manager"};
var mark = {name:"Mark", age:"21", sex:"Male", country:"US", position:"Designer"};
var jessica = {name:"Jessica", age:"19", sex:"Female", country:"UK", position:"Programmer"};

function showDetailsInLog(){
    console.log("Employee Name: " + this.name);
    console.log("Employee Age: " + this.age);
    console.log("Employee Sex: " + this.sex);
    console.log("Employee Country: " + this.country);
    console.log("Employee Position: " + this.position);
    console.log("-----------------------");
}

peter.logInfo = showDetailsInLog;
mark.logInfo = showDetailsInLog;
jessica.logInfo = showDetailsInLog;

peter.logInfo();
mark.logInfo();
jessica.logInfo();

这是使用“原型对象”教程

中的方法的项目
function Employee(n, a, s, c, p) {
    this.name = n;
    this.age = a;
    this.sex = s;
    this.country = c;
    this.position = p;
}

Employee.prototype.logInfo = function() {
    console.log("Employee Name: " + this.name);
    console.log("Employee Age: " + this.age);
    console.log("Employee Sex: " + this.sex);
    console.log("Employee Country: " + this.country);
    console.log("Employee Position: " + this.position);
    console.log("-----------------------");
}

var peter = new Employee("Peter", "23", "Male", "Russia", "Manager");
var mark = new Employee("Mark", "21", "Male", "US", "Designer");
var jessica = new Employee("Jessica", "19", "Female", "UK", "Programmer");

peter.logInfo();
mark.logInfo();
jessica.logInfo();

1 个答案:

答案 0 :(得分:2)

您的方法创建一个接受参数的全局函数(希望类型为employee)。然后,使用每个雇员对象作为参数,为每个对象调用该函数。

第二种方法将属性showDetailsInLog附加到每个雇员对象。为此属性分配全局函数showDetailsInLog,然后为每个雇员对象调用。

第三种方法使用函数构造函数来实例化一个雇员对象,该对象的原型包含一个logInfo函数,然后为每个对象调用该函数。

在这种情况下,我将使用第三种方法,因为代码正在创建同一对象的多个实例。