Javascript原型方法"无法设置属性"

Sam*_*amy 4 javascript prototype

我总是得到不能设置属性'saySomething'未定义,但为什么?我在某个地方犯了错误吗?

var Person = new Object();

Person.prototype.saySomething = function ()
{ 
  console.log("hello"); 
};

Person.saySomething();
Run Code Online (Sandbox Code Playgroud)

A.J*_*A.J 7

调试提示:..of undefined当您尝试访问某些未定义的属性时,会出现此错误.

当你这样做时new Object(),它会创建一个没有prototype属性的新空对象.

我不确定我们到底想要实现什么,但你可以访问函数原型并使用它.

var Person = function() {};

Person.prototype.saySomething = function() {
  console.log("hello");
};

var aperson = new Person();
aperson.saySomething();
Run Code Online (Sandbox Code Playgroud)


nem*_*035 5

prototype属性存在于函数中,而不存在于实例化对象上。

var Person = new Object();
console.log(Person.prototype); // undefined

var Person2 = function () {}
console.log(Person2.prototype); // {}
Run Code Online (Sandbox Code Playgroud)

这很有用,因为函数原型上的内容将由使用该函数创建的所有对象实例共享(使用new)。

var Person = function() {};

Person.prototype.saySomething = function() {
  console.log("hello");
};

console.log(
  new Person().saySomething === Person.prototype.saySomething // true. they are the same function
);
Run Code Online (Sandbox Code Playgroud)

如果您只想向person对象添加方法,则无需原型:

var Person = {};

Person.saySomething = function() {
  console.log("hello");
};

Person.saySomething();
Run Code Online (Sandbox Code Playgroud)

您甚至可以使用对象文字语法:

var Person = {
  saySomething: function() {
    console.log("hello"); 
  }
};

Person.saySomething();
Run Code Online (Sandbox Code Playgroud)