Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我应该在js的原型中声明构造函数吗? 功能用户(名称、电子邮件){ this.name=名称; this.email=theEmail; } User.prototype={ 构造函数:用户, 更改电子邮件:功能(新电子邮件){ this.email=newEmail; return“New Email Saved:”+this.Email; } } //使用者 firstUser=新用户(“Richard”Richard@examnple.com"); firstUser.changeEmail(“RichardB@examnple.com");_Javascript - Fatal编程技术网

Javascript 我应该在js的原型中声明构造函数吗? 功能用户(名称、电子邮件){ this.name=名称; this.email=theEmail; } User.prototype={ 构造函数:用户, 更改电子邮件:功能(新电子邮件){ this.email=newEmail; return“New Email Saved:”+this.Email; } } //使用者 firstUser=新用户(“Richard”Richard@examnple.com"); firstUser.changeEmail(“RichardB@examnple.com");

Javascript 我应该在js的原型中声明构造函数吗? 功能用户(名称、电子邮件){ this.name=名称; this.email=theEmail; } User.prototype={ 构造函数:用户, 更改电子邮件:功能(新电子邮件){ this.email=newEmail; return“New Email Saved:”+this.Email; } } //使用者 firstUser=新用户(“Richard”Richard@examnple.com"); firstUser.changeEmail(“RichardB@examnple.com");,javascript,Javascript,此代码取自此处: 问题: 是否有必要写这行:构造函数:用户,?如果我删除这条线,它仍然有效 当我们使用new操作符或{}在javascript中创建新对象时,新创建的对象的构造函数属性指向构造函数。就你而言: <script> function User (theName, theEmail) { this.name = theName; this.email = theEmail; } User.prototype = { constructor: Use

此代码取自此处:

问题:


是否有必要写这行:
构造函数:用户,
?如果我删除这条线,它仍然有效

当我们使用
new
操作符或
{}
在javascript中创建新对象时,新创建的对象的构造函数属性指向构造函数。就你而言:

<script>
function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
}

User.prototype = {
    constructor: User,
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}
// A User 
firstUser = new User("Richard", "Richard@examnple.com"); 
firstUser.changeEmail("RichardB@examnple.com");
</script>
firstUser.constructor
User

您的
用户也是如此。prototype
。使用
{}
User.prototype
创建新对象时,构造函数属性为
object
。当您放置
constructor:User
时,您只需将constructor属性从
Object
更改为
User
,您的代码仍然可以工作。

如果您用一个新对象替换默认原型,您只需这样做,就像对
User.prototype={…}
所做的那样。您只需扩展默认原型即可:

firstUser = new User("Richard", "Richard@examnple.com"); 

@埃德·赫勒:你的评论给讨论带来了什么?圣战挑衅?@Ed Heal:我的问题是-你为什么这样评论?这有助于OP解决他的问题,也有助于我们帮助OP解决他的问题?这个“事实”会改变解决方案中的某些东西吗?我知道你只是想和某人争论这个问题,但请不要这样做。@EdHeal:我想你只是混淆了这里的术语。面向对象编程独立于继承模型。JavaScript是完全面向对象的<代码>原型是继承的答案。让JS面向对象的是
这个
,就是它。@EdHeal:你说的“原型无法访问这个”是什么意思?@EdHeal:我想我们只是对OO语言有不同的概念。似乎“函数式语言”的定义也出现了同样的问题。我想说JavaScript既是面向对象的,也是功能性的。经典的继承和封装是对OO模式的补充。
User.prototype.changeEmail = function (newEmail)  {
   this.email = newEmail;
   return "New Email Saved: " + this.email;
}