gpt4 book ai didi

javascript - 这比。原型(prototype)

转载 作者:可可西里 更新时间:2023-11-01 01:17:05 25 4
gpt4 key购买 nike

<分区>

将方法“area”定义为“this”而不是“prototype”的属性有什么区别?

//console.clear()

function Rectangle(w, h)
{
this.width = w;
this.height = h;
this.area = function( ) { return this.width * this.height; }
}


var r = new Rectangle(2, 3);
var a = r.area( );

//console.log(a)

function Square(s)
{
this.side= s;
}

Square.prototype.area = function(){return this.side * this.side; }

var r = new Square(2);
var a = r.area( );

//console.log(a)

JavaScript - The definitive guideChapter 9 part 1Prototypes and Inheritance 部分,作者说定义方法原型(prototype)对象中的“区域”是有益的,但他的解释并不是很容易理解:

"..the area of every single Rectangle object always refers to the same function (someone might change it, of course, but you usually intend the methods of an object to be constant). It is inefficient to use regular properties for methods that are intended to be shared by all objects of the same class (that is, all objects created with the same constructor)."

我知道这个问题几乎看起来像 this一个,但它不是。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com