相关疑难解决方法(0)

原型继承 - 写作

所以我有这两个例子,来自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万
查看次数

何时使用IIFE与对象文字?

我即将开始为应用程序构建一个小的javascript模块.我已经接触过两种组织代码的方式:对象文字和IIFE.我知道,对于IIFE,所有变量和函数都保持私有,除非另有公开,但是还有其他原因我会在对象文字上使用它吗?

为什么我要使用对象文字:

var gojiraSays = 'Toxic Garbage Island!!!'

var app = {

  printStuff: function(){
    console.log(gojiraSays)
  }

}
Run Code Online (Sandbox Code Playgroud)

...说IIFE版本:

var app = (function(){
  var gojiraSays = 'Toxic Garbage Island!!!'

  var yellGojira = function(){
    console.log(gojiraSays);
  }

  return{
    yellGojira: yellGojira
  }

}());

app.yellGojira();
Run Code Online (Sandbox Code Playgroud)

javascript

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

使用javascript对象文字表示法定义函数

该线程描述了如何使用Javascript obect文字表示法来描述函数集合,例如:

var crudActions = {
    create : function () {
          ... 
    }
    read : function () {
          ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这个模式有名字吗?使用这种方法有优势吗?

javascript json function object-literal

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