Object.create()不能访问函数内部的变量

Object.create() cant access variable inside function

本文关键字:函数 内部 变量 访问 不能 create Object      更新时间:2023-09-26

我使用下面的代码。

var emp = function employee(name, sal) {
  this.empname = name;
  this.sal = sal;
}
emp.prototype.getName = function() {
  return this.empname
};
var man = new emp("manish", 100);
console.log(man.getName()); //prints manish
var man1 = Object.create(emp);
man1.empname = "manish1";
console.log(man1.prototype.getName()); //prints undefined.

可以帮助我理解为什么对象创建是打印未定义,而不是manish1。

new X()创建一个具有构造函数X和原型X.prototype的新对象。Object.create(X)创建一个原型为X的新对象(因此构造函数为X.constructor)。

所以你需要用原型来调用它你想要的:
var man2 = Object.create(emp.prototype);   
man2.empname = "manish2";
console.log (man2.getName()); // prints manish2