`
iandaicsu
  • 浏览: 52076 次
社区版块
存档分类
最新评论

javascript/ jQuery Best Practise

阅读更多

 

  • JS代码的良好的结构   https://tutsplus.com/lesson/slides-and-structure/             
  • 理解 JS 的 new 和 prototype 
    普通创建对象
var person = new Object();
person.firstName = "John";
person.lastName = "Deo";

person.sayHi = function(){
  return "Hi there";
};         
  
    使用Factory Function 创建对象
var createPerson = function(fristName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    sayHi : function() {
         return "Hi there";
    }
  };
};

var johnDeo = createPerson("John", "Deo");
var janeDeo = createPerson("Jane", "Deo");
  
    Constructor Functions and the Prototype, 重要的是函数F的 prototype 属性引用的原型对象 oldObject
function F(){};  
F.prototype = oldObject;  
var newObject = new F();    
    深入理解:Javascript基于原型的面向对象     http://blog.csdn.net/maybezi/article/details/9143559

 

    另外一种创建对象的方法

var Twitter = {
  init: function(){
    this.prop = "value";  
}
};
// only works in modern browsers
var twitter = Object.create(Twitter);

  

     
  •  注意禁用js的情况
  1. 首先写出一个html的页面,然后再进行添加javascript,因为有些人会禁用js。
  2.  $('html').addClass('js');    给html标记添加js tag,测试是否能够使用js。.js  container  和 container 分别来表示两种情况

 

  • 代码执行顺序
    按照普通的情况,是从上往下读取的。因此js代码应该放在body的最后。 
 
  • document ready的两种方法
$(document).ready(function(){
});
$( function(){} );   $() 中间放入function,自动执行document ready
 
 
  • 避免多次使用查询相同dom元素 
    var uls = $('ul');   cache it, so jQuery don't have to search it 3 times. 
 
  • JS的function,  call 和 apply 的区别 
  1. 相同点:call 和 apply 的作用是指定function中的this代表的是那个对象
  2. 区别: apply第二个参数是数组,call是单独添加的参数
theFunction.apply(valueForThis, arrayOfArgs)   ------------
theFunction.call(valueForThis, arg1, arg2, ...)

   

    3. sample code

function theFunction(name, profession) {
    alert("My name is " + name + " and I am a " + profession + ".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
 
  • Jquery data方法           refer to: http://api.jquery.com/data/
<div data-file= "123" ></div>
$(div).data(file)
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics