Discuss / JavaScript / 如果把hello写在student里面, 有什么不同吗?

如果把hello写在student里面, 有什么不同吗?

Topic source

如果把hello写在student里面, 有什么不同吗?

function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    };
}

江K60

#2 Created at ... [Delete] [Delete and Lock User]

同问!

Houtarchat

#3 Created at ... [Delete] [Delete and Lock User]

我个人认为是这样的,如有不对,还请多指教:

假设创建了一个对象

let xiaoming = new Student({name:'小明'});

此时hello方法是xiaoming这个对象的,

let xiaohong = new Student({name:'小红'});

xiaomingxiaohong都有一个叫hello的方法,但

xiaoming.hello === xiaohong.hello; // false

它们是两个不同的函数:每次创建一个新的对象,都会复制一次同样的方法;

如果通过new Student()创建了很多对象,就会占用很多内存

但实际上,xiaomingxiaohong完全可以共用同一个函数,而不需要再次创建

如果用Student.prototype.hello,此时函数hello位于Student.prototype原型上

根据对象的属性查找原则,xiaoming.hello();仍旧可以工作,而且不需要重新复制一次这个方法到xiaoming自身。


  • 1

Reply