相关疑难解决方法(0)

为什么有必要设置原型构造函数?

MDN文章面向对象的Javascript简介中关于继承部分中,我注意到他们设置了prototype.constructor:

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;  
Run Code Online (Sandbox Code Playgroud)

这有什么重要意义吗?省略它可以吗?

javascript oop inheritance

284
推荐指数
6
解决办法
5万
查看次数

JavaScript组织| 模块模式w /模块

我正在将代码组织成20-60行模块,通常是模块模式.我想要一个结构良好的面向对象的JavaScript库.

这是最好的方法吗?代码已经过测试和运行.

我喜欢它,因为程序员可以从库中提取模块并根据需要使用它们,它们是自包含的.

这是工具,消息,效果和文本,全部包含在NS中.

题?

这是组织我的图书馆的好方法(最佳实践)吗?

注意

到目前为止,评论和答案中有0个共识......非常令人沮丧.

外模块模式

var NS = ( function ( window, undefined ) 
{ 
/* All Modules below here */ 
} )( window );
Run Code Online (Sandbox Code Playgroud)

工具

/**
 *Tools
 *    getTimeLapse - benchmark for adding
 */

var Tool = ( function () 
{
    var Tool = function ( ) 
    {
    };
    Tool.prototype.getTimeLapse = function( numberOfAdds ) 
    {
        var end_time;
        var start_time = new Date().getTime();
        var index = 0;           
        while ( index <= numberOfAdds )
        {
            index++;
        } …
Run Code Online (Sandbox Code Playgroud)

javascript

5
推荐指数
1
解决办法
803
查看次数

什么是`constructor`属性真正用于什么?

在JavaScript中,每个函数的原型对象都有一个不可枚举的属性constructor,该属性指向函数(EcmaScript§13.2).它不用于任何本机功能(例如instanceof只检查原型链),但是我们鼓励在覆盖prototype函数的属性以进行继承时调整它:

SubClass.prototype = Object.create(SuperClass.prototype, {
    constructor: {value:SubClass, writable:true, configurable:true}
});
Run Code Online (Sandbox Code Playgroud)

但是,我们(包括我)是否只是为了清晰和整洁而这样做?是否存在依赖于该constructor属性的真实用例?

javascript constructor prototype

5
推荐指数
1
解决办法
585
查看次数

实现原型继承的正确方法

在JavaScript中已经有很多关于原型继承的线程,但由于懒惰,这不是副本.我已经完全阅读了所有内容,并且发现了几乎与我找到答案一样多的不同语法方法,所以看起来我并不是唯一一个对此主题感到困惑的人!

具体细节:

我目前的做法是这样的.

var Person = function(name) {
    this.name = name;

    this.greeting = function() {
        alert("Greetings, I am " + name);
    }

}

var bob = new Person("bob");
bob.greeting();

var Woman = function(name) {
    Person.call(this, name);
    this.gender = "female";
}

Woman.prototype = Object.create(Person.prototype);

var brenda = new Woman("brenda");
brenda.greeting();

Person.prototype.eats = true;

alert(brenda.eats);
Run Code Online (Sandbox Code Playgroud)

测试过代码之后我发现它完美无缺 - 据我所知 - 但我被告知这不是最好的方法,我应该像这样定义构造函数:

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

而不是在我的实际构造方法中使用Person.call方法.有两件事,被告知我看不到一个简单的方法,然后使用第二种方法传递参数,还有,为什么呢?我正在做的似乎工作得很好.

我错过了什么吗?

在某些情况下,我正在做的事情会给出不可预测的错误吗?

任何人都可以给出明确的"正确"方法及其原因吗?

javascript oop inheritance prototype

4
推荐指数
1
解决办法
137
查看次数

标签 统计

javascript ×4

inheritance ×2

oop ×2

prototype ×2

constructor ×1