gpt4 book ai didi

javascript - 在这里在 Javascript 中使用 "this"和 "prototype"有区别吗?

转载 作者:搜寻专家 更新时间:2023-11-01 04:28:00 26 4
gpt4 key购买 nike

下面两个代码有区别吗,我想没有。

function Agent(bIsSecret)
{
if(bIsSecret)
this.isSecret=true;

this.isActive = true;
this.isMale = false;
}

function Agent(bIsSecret)
{
if(bIsSecret)
this.isSecret=true;
}

Agent.prototype.isActive = true;
Agent.prototype.isMale = true;

最佳答案

至少在将非原始对象分配给 this.somevarprototype.somevar 时存在差异。

尝试运行这个:

function Agent(bIsSecret)
{
if(bIsSecret)
this.isSecret=true;

this.isActive = true;
this.isMale = false;
this.myArray = new Array(1,2,3);
}

function Agent2(bIsSecret)
{
if(bIsSecret)
this.isSecret = true;
}

Agent2.prototype.isActive = true;
Agent2.prototype.isMale = true;
Agent2.prototype.myArray = new Array(1,2,3);

var agent_a = new Agent();
var agent_b = new Agent();

var agent2_a = new Agent2();
var agent2_b = new Agent2();

if (agent_a.myArray == agent_b.myArray)
alert('agent_a.myArray == agent_b.myArray');
else
alert('agent_a.myArray != agent_b.myArray');

if (agent2_a.myArray == agent2_b.myArray)
alert('agent2_a.myArray == agent2_b.myArray');
else
alert('agent2_a.myArray != agent2_b.myArray');

关于javascript - 在这里在 Javascript 中使用 "this"和 "prototype"有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1748242/

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