关于原型的题目

Function.prototype.a = () => {
  console.log(1);
}
Object.prototype.b = () => {
  console.log(2);
}
function A() {}
const a = new A();

1 a.proto===> A.prototype 2 A.prototype.proto==>Object.prorotype 3 Object.prototype.proto 这个为 null,原型链查找到头。

题目2:

function A() { }

A.prototype.n = 0;

A.prototype.add = function () { this.n += 1; }

a = new A(); b = new A(); a.add(); console.log(b.add())

题目3:

function Person(name, age) { this.name = name; this.age = age; this.eat = function() { console.log(age + "岁的" + name + "在吃饭。"); } }

Person.run = function () {} // person 的 静态方法,不会出现在实例对象上 Person.prototype.walk = function () {}

let p1 = new Person("jsliang", 24); let p2 = new Person("jsliang", 24);

console.log(p1.eat === p2.eat); // false new 操作符使得构造函数内的 eat 函数(对象),是在堆中新开一份空间放置,所以两个实例对象它自然不共享。 console.log(p1.run === p2.run); // true undefined === undefinde console.log(p1.walk === p2.walk); // true p1.proto => Person.prototype =>Person.prototype.proto => null

静态属性和静态方法:我们可以把一个方法赋值给类的函数本身,而不是赋给它的 "prototype"。这样的方法被称为 静态的(static)。 特点: 静态方法被用于实现属于整个类的功能。它与具体的类实例无关。 静态方法用于实现属于该类但不属于该类任何特定对象的函数。 静态属性和方法是可被继承的。

class User { static staticMethod() { alert(this === User); } }

class User { }

User.staticMethod = function() { alert(this === User); // true };

在 User.staticMethod() 调用中的 this 的值是类构造器 User 自身(“点符号前面的对象”规则)。

上次更新:
贡献者: 郑壮