相关疑难解决方法(0)

在JavaScript中使用'prototype'与'this'?

有什么区别

var A = function () {
    this.x = function () {
        //do something
    };
};
Run Code Online (Sandbox Code Playgroud)

var A = function () { };
A.prototype.x = function () {
    //do something
};
Run Code Online (Sandbox Code Playgroud)

javascript prototype this

765
推荐指数
14
解决办法
11万
查看次数

原型继承 - 写作

所以我有这两个例子,来自javascript.info:

例1:

var animal = {
  eat: function() {
    alert( "I'm full" )
    this.full = true
  }
}

var rabbit = {
  jump: function() { /* something */ }
}

rabbit.__proto__ = animal 

rabbit.eat() 
Run Code Online (Sandbox Code Playgroud)

例2:

function Hamster() {  }
Hamster.prototype = {
  food: [],
  found: function(something) {
    this.food.push(something)
  }
}

// Create two speedy and lazy hamsters, then feed the first one
speedy = new Hamster()
lazy = new Hamster()

speedy.found("apple")
speedy.found("orange")

alert(speedy.food.length) // 2
alert(lazy.food.length) // 2 (!??)
Run Code Online (Sandbox Code Playgroud)

从示例2开始:当代码到达时 …

javascript inheritance prototype

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

JavaScript原型的好处

我一直在想JavaScript的原型性质及其好处,并且归结为以下列表:

1)继承

cat.prototype = animal
Run Code Online (Sandbox Code Playgroud)

2)内存效率

a.prototype.b = function() {}

var a1 = new a();
var a2 = new a();
Run Code Online (Sandbox Code Playgroud)

那么a1.b和a2.b本质上是同一个对象,其中:

var a = function() {
             this.b = function() {}; 
        }

var a1 = new a();
var a2 = new a();
Run Code Online (Sandbox Code Playgroud)

a1.b和a2.b将是不同的函数对象并占用更多内存.

3)将方法/字段添加到已经创建的多个"野外"对象中.

var a = function() {}

var a1 = new a();
var a2 = new a();

a.prototype.b = function() {}

a1.b();
a2.b();
Run Code Online (Sandbox Code Playgroud)

所以问题是,这些是正确的吗?

......还有其他任何我错过的好处吗?

干杯!

javascript prototype

11
推荐指数
1
解决办法
3001
查看次数

标签 统计

javascript ×3

prototype ×3

inheritance ×1

this ×1