相关疑难解决方法(0)

Javascript构造函数属性的意义是什么?

试图绕过Javascript对OO的看法......和许多其他人一样,对constructor财产产生混淆.特别是constructor财产的重要性,因为我似乎无法使其产生任何影响.例如:

function Foo(age) {
    this.age = age;
}

function Bar() {
    Foo.call(this, 42);
    this.name = "baz"; 
}

Bar.prototype = Object.create(Foo.prototype); 
var b = new Bar;    

alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name);        // "baz". Shows that Bar() was called as constructor.
alert(b.age);         // "42", inherited from `Foo`.
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,对象b似乎有正确的构造函数call(Bar) - 并且它继承了age属性Foo.那么为什么许多人认为这是必要的步骤:

Bar.prototype.constructor = Bar;
Run Code Online (Sandbox Code Playgroud)

显然,Bar构造时会调用正确的构造函数b,因此这个原型属性有什么影响?我很想知道它实际上使构造函数属性设置'正确'有什么实际区别 - 因为我无法看到它对创建对象后实际调用的构造函数有任何影响.

javascript constructor prototype

118
推荐指数
4
解决办法
2万
查看次数

JavaScript 中的类与函数构造函数

背景:C# 开发人员最近深入研究 javascript

以下是在 JavaScript 中创建对象的两种方法。它们之间有什么区别,创建对象时我应该使用/优先考虑哪种方法,为什么?

class John {
    constructor(name, birth, height) {
        this.name = name;
        this.birth = birth;
        this.height = height;} }

var Person = function(name, birth, height) {
    this.name = name;
    this.birth = birth;
    this.height = height;}
Run Code Online (Sandbox Code Playgroud)

javascript

2
推荐指数
1
解决办法
2303
查看次数

标签 统计

javascript ×2

constructor ×1

prototype ×1